如果过滤器排除了孩子的父母,他们如何在array.filter()回调函数中获取它们?

时间:2017-11-21 22:37:14

标签: javascript jquery arrays

今天我发现了array.filter()方法及其相关的回调函数。

我有一个对象数组,如下所示:

var treeAry = [
      {"id" : "200", "parent": "#", "type" : "1"},
      {"id" : "300", "parent": "#", "type" : "1"},
      {"id" : "400", "parent": "#", "type" : "1"},
      {"id" : "500", "parent": "300", "type" : "5"},
      {"id" : "600", "parent": "300", "type" : "5"},
      {"id" : "700", "parent": "400", "type" : "5"},
      {"id" : "800", "parent": "400", "type" : "5"},
      {"id" : "900", "parent": "200", "type" : "6"},
      {"id" : "1000", "parent": "200", "type" : "9"},
      {"id" : "1100", "parent": "200", "type" : "8"},
];

我成功地过滤了类型5:

  filteredAry = [];

  filteredAry = treeAry.filter(function(val, index, ary){

    /*get all type 5*/
    return val.type === '5';

    /*get all type 5 or type 1*/
    //return val.type === '1' || val.type === '5';

  });

  console.dir(filteredAry)

这是我的问题:

虽然我可以过滤类型5,但我还需要5型父母(孩子的parent引用id和{{{ 1}}可以是#)。基本上,我的结果应该包含类型5的任何内容,然后还记录parentid 300不应包含400

我应该为id 200上的每个循环运行某种类型来查找并推送filteredAry[]中的相应项吗?难道我不能使用treeAry[]index参数以某种方式让父母知道吗?

抱歉,我不知道如何做到这一点并且会非常感谢你的帮助。只需要朝着正确的方向努力,谢谢!

2 个答案:

答案 0 :(得分:3)

试试这个:

var treeAry = [
      {"id" : "200", "parent": "#", "type" : "1"},
      {"id" : "300", "parent": "#", "type" : "1"},
      {"id" : "400", "parent": "#", "type" : "1"},
      {"id" : "500", "parent": "300", "type" : "5"},
      {"id" : "600", "parent": "300", "type" : "5"},
      {"id" : "700", "parent": "400", "type" : "5"},
      {"id" : "800", "parent": "400", "type" : "5"},
      {"id" : "900", "parent": "200", "type" : "6"},
      {"id" : "1000", "parent": "200", "type" : "9"},
      {"id" : "1100", "parent": "200", "type" : "8"},
];

var result = treeAry.filter(value => {
	return value.type === '5' || treeAry.filter(val => val.parent === value.id && val.type === '5').length > 0;
});

console.log(result)

如果ES6是个问题,你可以用普通函数替换lambdas(箭头函数)。

答案 1 :(得分:1)

一种方法是

var treeAry = [
      {"id" : "200", "parent": "#", "type" : "1"},
      {"id" : "300", "parent": "#", "type" : "1"},
      {"id" : "400", "parent": "#", "type" : "1"},
      {"id" : "500", "parent": "300", "type" : "5"},
      {"id" : "600", "parent": "300", "type" : "5"},
      {"id" : "700", "parent": "400", "type" : "5"},
      {"id" : "800", "parent": "400", "type" : "5"},
      {"id" : "900", "parent": "200", "type" : "6"},
      {"id" : "1000", "parent": "200", "type" : "9"},
      {"id" : "1100", "parent": "200", "type" : "8"},
];

  filteredAry = [];
  filteredAry = treeAry.filter(function(val, index, ary){
    /*get all type 5*/
    return val.type === '5' || 
           ary.some(function(item){ 
                return item.parent === val.id && item.type==='5';
              });


  });

  console.dir(filteredAry)