通过JavaScript按其项属性过滤列表

3
我可以通过以下方式筛选出纯净的列表:
var list = [1, 2, 3, 4, 5, 1, 3]

function list_filter(list, value) {

  return list.filter(function (item) {
    if (item === value) {
      return true
    }
  })

}

console.log(list_filter(list, 1))  // there will print `[1, 1]`

但是我对过滤器还有进一步的要求,如下所示:
var a = [

  {a:'1', b:"2", c:3, d: {id:'d1'}},
  {a:'1', b:"2", c:3, d: {id:'d2'}},
  {a:'1', b:"2", c:3, d: {id:'d1'}},
  {a:'1', b:"2", c:3, d: {id:'d3'}},
  {a:'1', b:"2", c:3, d: {id:'d3'}},
  {a:'1', b:"2", c:3, d: {id:'d4'}}
]

我希望按照item.d.id对列表进行筛选。

我想要这样使用list_filter

function list_filter(list, 'd.id', value) ... // the value is the filter id

或者:

function list_filter(list, ['d', 'id'], value) ... 

我的意思是,
list_filter(a, ['d', 'id'], 'd1') 

获取筛选后的列表。 ['d', 'id'] 可能会变成 ['d', 'e', 'id'] 或者更长。


那么你的问题是什么?如何通过一个字符串数组作为路径来访问嵌套属性? - Sebastian Simon
可能是 使用字符串数组作为路径动态访问嵌套对象 的重复问题。 - Sebastian Simon
3个回答

3
您可以使用 .filter 以及内部的 reduce 来确定目标值:

var a=[{a:'1',b:"2",c:3,d:{id:'d1'}},{a:'1',b:"2",c:3,d:{id:'d2'}},{a:'1',b:"2",c:3,d:{id:'d1'}},{a:'1',b:"2",c:3,d:{id:'d3'}},{a:'1',b:"2",c:3,d:{id:'d3'}},{a:'1',b:"2",c:3,d:{id:'d4'}}];
const list_filter = (arr, keyArr, value) => (
  arr.filter(obj => (
    value === keyArr.reduce((currObj, key) => currObj[key], obj)
  )
));

console.log(list_filter(a, ['d', 'id'], 'd3'));


0
你可以使用本地的 Array#filter 方法并添加一个 for ... of 循环来遍历你的路径:

let data = [
  {a:'1', b:"2", c:3, d: {id:'d1'}},
  {a:'1', b:"2", c:3, d: {id:'d2'}},
  {a:'1', b:"2", c:3, d: {id:'d1'}},
  {a:'1', b:"2", c:3, d: {id:'d3'}},
  {a:'1', b:"2", c:3, d: {id:'d3'}},
  {a:'1', b:"2", c:3, d: {id:'d4'}}
];

const list_filter = (arr, path, val) => {
  return arr.filter(e => {
    let field = e;
    for(let currentPath of path) field = field[currentPath];
    return field == val;
  });
};

console.log(list_filter(data, ['d', 'id'], 'd1'));


0

与其传递一个用点分隔的字符串键或键数组,我建议采用接受函数来选择每个项值的签名方法:

const a = [
  {a:'1', b:'2', c:3, d: {id:'d1'}},
  {a:'1', b:'2', c:3, d: {id:'d2'}},
  {a:'1', b:'2', c:3, d: {id:'d1'}},
  {a:'1', b:'2', c:3, d: {id:'d3'}},
  {a:'1', b:'2', c:3, d: {id:'d3'}},
  {a:'1', b:'2', c:3, d: {id:'d4'}}
]

function filter_list (array, selector, value) {
  return array.filter(
    item => selector(item) === value
  )
}

console.log(filter_list(a, o => o.d.id, 'd1'))
// or
console.log(filter_list(a, ({d:{id}}) => id, 'd1'))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接