Lodash通过匹配ids数组从数组中删除对象

Git*_*bia 10 javascript arrays lodash

我有一组对象,如:

var a = [
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 3,  name: 'C'},
  {id: 4, name: 'D'}
];
Run Code Online (Sandbox Code Playgroud)

和Ids数组我想从数组中删除a:

var removeItem = [1,2];
Run Code Online (Sandbox Code Playgroud)

我想array a通过匹配removeItem array包含的ID 来删除对象.我怎么能用lodash实现.

我检查了lodash的_.remove方法,但这需要一个特定的条件来从数组中删除一个项目.但我有我要删除的ID列表.

Gab*_*oli 8

正如您所提到的,您需要的_.remove方法和您提到的具体条件是removeItem数组是否包含数组id的checked元素.

var removeElements = _.remove(a, obj => removeItem.includes(obj.id));
// you only need to assign the result if you want to do something with the removed elements.
// the a variable now holds the remaining array
Run Code Online (Sandbox Code Playgroud)