我有两个数组
var a = ['tayyar', '14march' ];
和
b = [{
"feedsource": "tayyar",
"hash": "46cc3d067df1ea7877140c67b60e9a7a"
}, {
"feedsource": "elmarada",
"hash": "a9fb75f2aa4771945ec597ecf9ae49ea"
}, {
"feedsource": "14march",
"hash": "fce7a6a87b53358c4be47507b0dc327b"
}, {
"feedsource": "tayyar",
"hash": "b85d2a9c22ac4831477de15ba24b4ac5"
}]
我想要从b中未定义其feedource的b中删除对象。
到目前为止,我已经尝试了
b.forEach(function(e) {
var indexVal = b.indexOf(e);
if(a.indexOf(e.feedsource) ==-1){
console.log(e.feedsource);
b.splice(indexVal,1);
}
});
但它似乎不起作用,我仍然看到不应该存在的元素以及应该删除的元素。我的功能在做什么?
答案 0 :(得分:2)
更好的解决方案是不改变原始数组,而是创建一个新的过滤数组。幸运的是,JavaScript提供.filter()
来帮助您!
var c = b.filter(function(el) {
// Only keep those where the following is true
return a.indexOf(el.feedsource) > 0;
});
答案 1 :(得分:0)