如果其中一个属性包含某些值,请删除数组元素

时间:2018-09-20 16:53:49

标签: javascript lodash

我有以下变量:

var data = [{id: '1', name: 'demo1'}, {id: '2', name: 'demo2'}, {id: '3', name: 'demo3'}]

现在我还有另一个id列表,

var lookFor = ["2", "3"];

现在,如何从data删除id的{​​{1}}数组中没有的lookFor的对象。

我尝试了

id

还有其他方法吗?

4 个答案:

答案 0 :(得分:1)

嗯,请考虑以下内容?

var data = [{id: '1', name: 'demo1'}, {id: '2', name: 'demo2'}, {id: '3', name: 'demo3'}];
var keys = ["2", "3"];

let filteredArray = data.filter(element => keys.indexOf(element.id) != -1);
console.log(filteredArray);

// Output is now 
// 0: {id: "2", name: "demo2"}
// 1: {id: "3", name: "demo3"}

与此相反:

let filteredArray = data.filter(element => keys.indexOf(element.id) == -1);
console.log(filteredArray);

// Output is:
// 0: {id: "1", name: "demo1"}

这就是你想要的吗?

祝你有美好的一天,伊莱亚斯

答案 1 :(得分:0)

您可以将functor filter用于数组,并将方法includes用于

  

确定数组是否包含某个元素

 var res =  data.filter(el=>!lookFor.includes(el.id));

结果

 [{id: "1", name: "demo1"}]

相反

var res =  data.filter(el=>lookFor.includes(el.id));

答案 2 :(得分:0)

您可以按以下方式使用_.remove(array, [predicate=_.identity])。请注意,这会改变data的值。

var data = [{id: '1', name: 'demo1'}, {id: '2', name: 'demo2'}, {id: '3', name: 'demo3'}];

var lookFor = ["2", "3"];

_.remove(data, function(n) {
  return _.indexOf(lookFor, n.id) === -1;
});

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

答案 3 :(得分:0)

这里仅是几个示例,说明如何仅使用ES6或使用lodash来实现此目的。显然有更多的方法可以执行此操作,但是这些方法应该可以给您一个想法。还要注意,大多数示例do not都会对使用的数组进行突变:

var data = [{id: '1', name: 'demo1'}, {id: '2', name: 'demo2'}, {id: '3', name: 'demo3'}]
var lookFor = ["2", "3"];

// Does not mutate the array and uses ES6 Filter
var withFilter = data.filter(x => lookFor.indexOf(x.id) >= 0)

// Does not mutate the array and uses ES6 Reduce
var withReduce = lookFor.reduce((r,c) => r.push(data.find(x => x.id === c) || []) && r,[])

// Does not mutate the array with Lodah Filter
var withLodashFilter = _.filter(data, x => _.includes(lookFor, x.id))

// Mutates the array with Lodash Remove
var withLodashRemove = _.remove(data, x => _.includes(lookFor, x.id))

console.log('ES6 Filter', withReduce)
console.log('ES6 Reduce', withFilter)
console.log('Lodah Filter', withLodashFilter)
console.log('Lodash Remove', withLodashRemove)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>