I want to remove object from array that matches the id
from array, like this one
我想从数组中移除对象,它与数组中的id相匹配,比如这个。
var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title: "title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];
I just want to remove an object that matches in an array. The result that I expected is like
我只是想要移除一个数组中匹配的对象。我期望的结果是。
var report = [{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
I have used .splice.
method on .forEach
but it seems doesn't work so well.
我用.splice。方法。foreach,但它似乎不太好用。
Any help will be appreciated :)
如有任何帮助,我们将不胜感激:
3 个解决方案
#1
0
You can use filter()
and indexOf()
您可以使用filter()和indexOf()
var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title: "title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];
var result = report.filter(function(e) {
return array.indexOf(e.id) == -1;
})
console.log(result)
#2
0
var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title:"title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];
var newReport = report.filter(function(item){
return array.indexOf(item.id) == -1;
})
#3
0
A solution with .splice()
(but without .forEach()
)
一个带.splice()的解决方案(但是没有。foreach ())
var report = [
{ id: 1, title: "title 1" },
{ id: 2, title: "title 2" },
{ id: 3, title: "title 3" },
{ id: 4, title: "title 4" },
{ id: 5, title: "title 5" }
];
var array = [1, 2, 3];
// "walk" backwards to circumvent the problem of the changing length because of .splice()
for (var i = (report.length - 1); i >= 0; i--) {
if (array.indexOf(report[i].id) > -1) {
report.splice(i, 1);
}
}
console.log(report);
#1
0
You can use filter()
and indexOf()
您可以使用filter()和indexOf()
var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title: "title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];
var result = report.filter(function(e) {
return array.indexOf(e.id) == -1;
})
console.log(result)
#2
0
var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title:"title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];
var newReport = report.filter(function(item){
return array.indexOf(item.id) == -1;
})
#3
0
A solution with .splice()
(but without .forEach()
)
一个带.splice()的解决方案(但是没有。foreach ())
var report = [
{ id: 1, title: "title 1" },
{ id: 2, title: "title 2" },
{ id: 3, title: "title 3" },
{ id: 4, title: "title 4" },
{ id: 5, title: "title 5" }
];
var array = [1, 2, 3];
// "walk" backwards to circumvent the problem of the changing length because of .splice()
for (var i = (report.length - 1); i >= 0; i--) {
if (array.indexOf(report[i].id) > -1) {
report.splice(i, 1);
}
}
console.log(report);