今天我发现了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的任何内容,然后还记录parent
和id 300
。 不应包含400
。
我应该为id 200
上的每个循环运行某种类型来查找并推送filteredAry[]
中的相应项吗?难道我不能使用treeAry[]
和index
参数以某种方式让父母知道吗?
抱歉,我不知道如何做到这一点并且会非常感谢你的帮助。只需要朝着正确的方向努力,谢谢!
答案 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)