对于有经验的人来说,这可能是非常基本的。这是我第一次使用下划线。我有这个json。
{
"especiais" : {
"text" : {
"pt" : "Especiais"
},
"active" : true
},
"conjuntos" : {
"text" : {
"pt" : "Conjuntos"
},
"active" : true,
"subItems" : {
"saiaEcamiseta" : {
"text" : {
"pt" : "Saia e Camiseta"
},
"active" : true
},
"sandalhas" : {
"text" : {
"pt" : "Sandalhas"
},
"active" : true
}
}
},
"macacoes" : {
"text" : {
"pt" : "Macacões"
},
"active" : true
},
"roupasBasicas" : {
"text" : {
"pt" : "Roupas Básicas"
},
"active" : true,
"subItems" : {
"xortes" : {
"text" : {
"pt" : "Xortes"
},
"active" : true
},
"camiseta" : {
"text" : {
"pt" : "Camisetas"
},
"active" : true
}
}
},
"enxoval" : {
"text" : {
"pt" : "Enxoval"
},
"active" : true
}
}
我只想列出iten和子项的活动根。因此,在上面的例子中,猕猴和他的孩子将不会被列入名单,Xortes(roupasBasicas的孩子)也不会被列入,如果适用的话,它包括可能的孙子。
我第一次尝试:
result = _und.filter(data.productCategories, function (item) {
return item && item.active.indexOf(true) != -1;
});
但它不起作用:(有人能帮我吗?
由于缺乏声誉,我无法要求澄清,所以我会尽力为您找到答案。
var children = [];
//Get all of the subitems that are active so we can merge with the primary result set
_.each(data.pt, function(item){
if(item.subItems){
_.each(item.subItems, function(child){
if(child.active) children.push(child);
});
}
});
//Gather all active items in the primary result set
var result = _.filter(data.pt, function(item){
return item.active;
});
//Add each active subItem to our results
_.each(children, function(child){
result.push(child);
});
以下是我的理解:http://plnkr.co/edit/qx6U6ZcmcfhqJxmNulzP?p=preview--看看script.js,因为它将提供核心实现。
根据我的理解,您希望在pt对象的上下文中收集所有"活动"项?
如果是这样的话,我通过链接提供的过滤器会很好,尽管你仍然会在父项下面有项目。
如果需要过滤这些数据,你可以简单地将数据附加到对象的字段置空(如果你选择的话,也可以用更聪明的方法)。
_.filter
函数似乎最适合这种情况,因为您可以过滤给定谓词的数据集。上述代码中提供的查询I的第二部分中的函数根据原始数据集是否处于活动状态来缩小原始数据集的范围。