我有一个包含对象的JavaScript数组和一个包含一些ID的数组。我想要的是比较数组中的对象与id数组,如果在对象中找到任何id,我想从数组中删除该元素。执行此操作后,结果将显示undefined以代替已删除的元素。
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}]
var arr = ["2","5"];
for (var i = 0; i < data.length; i++) {
for(var j=0;j<arr.length;j++){
if (arr[j]==data[i].id ) {
delete data[i];
}
}
}
结果显示[undefined,object object,object object,undefined]
。有没有办法只获得[object object,object object]
?
答案 0 :(得分:0)
splice
代替delete
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}];
var arr = ["2","5"];
for (var i = data.length-1; i >= 0; i--) {
for(var j = 0;j < arr.length;j++){
if (arr[j]==data[i].id ) {
data.splice(i,1);
}
}
}
console.log(data);