var array = [{
name: "Mango",
weight: "15gm"
}, {
name: "Banana",
weight: "10gm"
}, {
name: "Apple",
weight: "15gm"
}, {
name: "Grapes",
weight: "5gm"
}, {
name: "Banana",
weight: "15gm"
}];
我想删除除香蕉以外的所有内容。
答案 0 :(得分:2)
请参阅here。
array.filter(function(x) {
return x.name == "Banana";
});
所以给出了这个输入:
[{"name":"Mango","weight":"15gm"},{"name":"Banana","weight":"10gm"},{"name":"Apple","weight":"15gm"},{"name":"Grapes","weight":"5gm"},{"name":"Banana","weight":"15gm"}]
我们得到了这个输出:
[{"name":"Banana","weight":"10gm"},{"name":"Banana","weight":"15gm"}]
答案 1 :(得分:1)
在上面的数组中,当我使用splice方法删除数组元素时,我的数组长度减1,所以我必须考虑索引i。以下是删除此类对象的代码。
for(var i=0;i<array.length;i++){
if(array[i].name !== "Banana"){
array.splice(i,1);
i--;
}
}