我有嵌套数组,需要根据条件删除对象。
阵列:
grouplist: [
{
name: "one",
optionlist: [
{
optionitem: "green"
},
{
optionitem: "red"
}
]
},
{
name: "two",
optionlist: [
{
optionitem: "yellow"
},
{
optionitem: "red"
},
{
optionitem: "blue"
}
]
},
{
name: "three",
optionlist: [
{
optionitem: "green"
}
]
},
{
name: "four",
optionlist: [
{
optionitem: "blue"
},
{
optionitem: "red"
}
]
}
];
如果optionItem颜色为绿色,那么我需要从数组对象中完全删除它。
这就是我的尝试。
var returnedData = _.filter(grouplist, function(n) {
return _.some(n.optionlist, function(option){
return option.optionitem!= "green";
});
});
答案 0 :(得分:3)
var returnedData = _.filter(grouplist, function(n){
var containsGreen = _.some(n.optionlist, function(option){
return option.optionitem === "green";
})
return !containsGreen;
});
答案 1 :(得分:1)
var returnedData = _.reject(grouplist, function(n){
return _.some(n.optionlist, function(option){
return option.optionitem === "green";
});
});
答案 2 :(得分:0)
filter
或_.filter
的问题在于您正在创建新数组。如果你想简单地从现有数组中删除一个对象而不创建一个新对象,这里有一个简单的vanilla JS方法,用相同数量的代码行完成:
for (var i = 0, l = grouplist.length; i < l; i++) {
var foundGreen = grouplist[i].optionlist.some(function (el) {
return el.optionitem === 'green';
});
if (foundGreen) grouplist.splice(i, 1); i--; l--;
}