简体   繁体   English

如果 array2 没有相同的 object 键值,则从对象数组 (array1) 中删除 object

[英]Remove object from array of objects (array1) if array2 does not have the same object key value

I have two array of objects arr1 and arr2.我有两个对象数组 arr1 和 arr2。

enter code here
const arr1 = [
   {name: 'Jake', age: 17},
   {name: 'Mike', age: 15},
   {name: 'Ryan', age: 18},
 ];

 const arr2 = [
   {name: 'Milo', age: 17},
   {name: 'Rem', age: 18},
   {name: 'Oliver', age: 19},
 ];

I want to remove objects in arr1 that does not have key value that arr2 has.我想删除 arr1 中没有 arr2 具有的键值的对象。 I tried this, but no success:我试过这个,但没有成功:

const arr3 = this.arr1.filter(x => {
   let z = this.arr2.find(y => y.age== x.age)
   if (z) {
      return x;
   }
});

My expected array is this:我预期的数组是这样的:

array3 = [
  {name: 'Jake', age: 17},
  {name: 'Ryan', age: 18},
];

You just have to remove this from the variables.您只需从变量中删除this Also, you can shorten the return statements like this:此外,您可以像这样缩短返回语句:

 const arr1 = [ {name: 'Jake', age: 17}, {name: 'Mike', age: 15}, {name: 'Ryan', age: 18}, ]; const arr2 = [ {name: 'Milo', age: 17}, {name: 'Rem', age: 18}, {name: 'Oliver', age: 19}, ]; const arr3 = arr1.filter(x => z = arr2.find(y => y.age== x.age)); console.log(arr3)

However, if you want keep this you can declare the variables using var and then this.arr will be referring to window.arr and the code will still work as var creates a property on the global object while const or let do not:但是,如果您想保留this ,您可以使用var声明变量,然后this.arr将引用window.arr并且代码仍然可以工作,因为 var 在全局 object 上创建属性,而 const 或 let 不要:

 var arr1 = [ {name: 'Jake', age: 17}, {name: 'Mike', age: 15}, {name: 'Ryan', age: 18}, ]; var arr2 = [ {name: 'Milo', age: 17}, {name: 'Rem', age: 18}, {name: 'Oliver', age: 19}, ]; const arr3 = this.arr1.filter(x => z = this.arr2.find(y => y.age== x.age)); console.log(arr3)

The Array.阵列。 some methods returns a boolean value which it slightly more appropriate. some方法返回一个 boolean 值,它稍微更合适一些。 However find works too since non-null/undefined are treated as thruthy.但是find也有效,因为非空/未定义被视为 thruthy。 If you arrays are truly in a class, then:如果您的 arrays 确实在 class 中,则:

const arr3 = this.arr1.filter(x => this.arr2.some(y => y.age === x.age));

Otherwise need to remove this :否则需要删除this

const arr3 =arr1.filter(x => arr2.some(y => y.age === x.age));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM