使用特定键获取对象数组中的所有值(set :: extract cakephp等效项)

时间:2015-08-03 16:27:45

标签: javascript

是否有相当于cakePHPs set :: extract功能(http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::extract)?

我得到的是这样的:

var arr = [{name: "test", children: [id: 1, title: "title1"]},
           {name: "test2", children: [id: 2, title: "title2"]}, 
           {name: "lipsum", children: [id: 1, title: "title1", id: 2, title: "title2"]},
           {name: "lipsum2", children: [id: 3, title: "title3"]}]

我想做的是:

var objs = filter({arr.children.id:1});

'objs'的结果应该是:

[{name: "test", children: [id: 1, title: "title1"]},
 {name: "lipsum", children: [id: 1, title: "title1", id: 2, title: "title2"]}]

提前致谢。

2 个答案:

答案 0 :(得分:0)

您的对象结构无效......子数组实际上应该是一个对象。然后你可以这样做:

var filtered = arr.filter(function(item) {
    return item.children.filter(function(child) {
        return child.id === 1;
    }).length
});

正确的数据格式:

[{
    name: "test", 
    children: [{
        id: 1, 
        title: "title1"
    }]
}]

演示:http://jsfiddle.net/588o5p69/

答案 1 :(得分:0)

JS中数组的正确结构必须是这样的:

var arr = [{name: "test", children: [ {id: 1, title: "title1" } ]},
           {name: "test2", children: [ { id: 2, title: "title2" } ]}, 
           {name: "lipsum", children: [ {id: 1, title: "title1"}, {id: 2, title: "title2"}]},
           {name: "lipsum2", children: [ {id: 3, title: "title3"} ]}];

在该结构上,您只需使用underscore's _.filter

var resArr= _.filter(arr, function(elem){ return elem.children.id === 1; });

如果IE< 9与您无关,您也可以使用ECMA Script 5's native filter function

var resArr= arr.filter(function(elem){ return elem.children.id === 1; });