如何从数组中删除除匹配值以外的对象?

时间:2019-09-27 04:14:53

标签: javascript arrays

我正在尝试根据不匹配的值从数组中删除对象。

这是我的物品数组:

var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

var arr=["88","108"];

这里我可以根据匹配的值从数组中删除对象。但是我想保留匹配的值对象,并且需要删除不匹配的对象。

这就是我要从数组中删除匹配对象的方式。

for(let i in arr) {
  items = items.filter(function(item) {
    return item.id !== arr[i];
  });
}

5 个答案:

答案 0 :(得分:1)

使用indexOf确定事件的发生。

var items = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

var arr=["88","108"];

const filteredItems = items.filter(item => {
  if (arr.indexOf(item.id)>-1) {
    return item
    }
})

console.log(filteredItems)

答案 1 :(得分:1)

您可以将Array.filterArray.includes一起使用:

var items = [{"id":"88","name":"Lets go testing"},{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}];
var arr = ["88", "108"];

const result = items.filter(item => arr.includes(item.id));
console.log(result);

答案 2 :(得分:1)

items = items.filter(function(item) {
    return arr.indexOf(item._id)!=-1
  });

答案 3 :(得分:1)

您可以将items数组转换为查找表(指向实际对象的id对象),然后将.map()分别转换为arr。如果您在itemsarr中有大量数据,此方法特别有用:

const items = [{"id":"88","name":"Lets go testing"},{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}];

const lut = items.reduce((acc, obj) => ({...acc, [obj.id]: obj}), {});
const arr = ["88", "108"];

const result = arr.map(id => lut[id]);
console.log(result);

答案 4 :(得分:0)

解决方案-

var items = [
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
];
var arr = ["88","108"];
items = items.filter( (item) => arr.includes(item.id) );