我有一个这样的集合:
var collection={
"Today": [{
"id": "1",
"name": "iPod Nano",
"image": "img/items/item1.jpg",
"special": 0
}, {
"id": "2",
"name": "Samsung TV",
"image": "img/items/item2.jpg",
"special": 1
}],
"Monday 11 August 2014": [{
"id": "3",
"name": "Nikon Camera",
"image": "img/items/item3.jpg",
"special": 0
}, {
"id": "4",
"name": "iPad 1000",
"image": "img/items/item4.jpg",
"special": 0
}],
"Monday 30 August 2014 ": [{
"id": "5",
"name": "ar of Gold",
"mage": "img / items / item5.jpg ",
"special ": 1
}, {
"id ": "6 ",
" name ": "Buzz Light Year ",
"image ": " img / items / item6.jpg ",
"special ": 1
}]
};
我想过滤收藏并保持特殊== 1:
我试过了:
var Specials=_.reduce(collection,function(memo,item){
var result = _.filter(item,function(c){
return c.special==0 ;
});
if(result.length > 0 ){
var newResult = {};
newResult.deals = result;
newResult.id = item.id;
memo = _.union(memo,newResult);
}
return memo;
},[]);
var jsonText=JSON.stringify(Specials);
console.log("=========>" + jsonText);
但没有达到我的预期。
为什么呢?我希望结果如下:
var filtered={
"Today": [{
"id": "2",
"name": "Samsung TV",
"image": "img/items/item2.jpg",
"special": 1
}],
"Monday 30 August 2014 ": [{
"id": "5",
"name": "ar of Gold",
"mage": "img / items / item5.jpg ",
"special ": 1
}, {
"id ": "6 ",
" name ": "Buzz Light Year ",
"image ": " img / items / item6.jpg ",
"special ": 1
}]
};
答案 0 :(得分:2)
我记得还有其他功能,
如果您需要保持相同的JSON结构,可以使用每个 + 拒绝 fiddle
_.each(collection, function(items, key){
var filtered = _.reject(items, function(item){
return item.special < 1
});
if(filtered.length){
specials[key] = filtered;
}
});
答案 1 :(得分:1)
您可以尝试:
var collection = {
"Today": [
{
"id": "1",
"name": "iPod Nano",
"image": "img/items/item1.jpg",
"special": 0
},
{
"id": "2",
"name": "Samsung TV",
"image": "img/items/item2.jpg",
"special": 1
}
],
"Monday 11 August 2014": [
{
"id": "3",
"name": "Nikon Camera",
"image": "img/items/item3.jpg",
"special": 0
},
{
"id": "4",
"name": "iPad 1000",
"image": "img/items/item4.jpg",
"special": 0
}
]
};
for(var i in collection){
collection[i] = _.filter(collection[i], function(item){
return item.special == 0;
});
}
console.log(collection);
结果将按天分组,如果要合并,则必须编写此
var res = [];
for(var j in collection){
for(var i = 0; i < collection[j].length; i++)
res.push(collection[j][i]);
}
console.log(res);