在javascript中按项目的属性过滤列表

时间:2018-05-21 07:39:08

标签: javascript

我可以通过以下方式过滤纯列表:

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']或更长。

3 个答案:

答案 0 :(得分: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'));

答案 1 :(得分:0)

您可以使用原生的Array#filter方法并添加一条贯穿您路径的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'));循环:

{{1}}

答案 2 :(得分: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'))