如何检查数组的所有对象是否包含另一个数组?

时间:2019-01-10 08:11:51

标签: javascript arrays angular typescript object

我正在尝试检查对象array A是否包含来自objects的{​​{1}}。

B

因此let A = [ { name: "Max" }, { name: "Jhon" }, { name: "Naton" }, ] let B = [ { name: "Max" }, { name: "Naton" }, ] 有两个B中的objects。如何检查呢?

我正在尝试通过array A实现它:

includes

但是我在 for(let entry of this.b){ if(this.a.includes(entry)){ console.log('includes'); } } 上得到了false

3 个答案:

答案 0 :(得分:3)

您必须使用另一个循环,然后检查属性名称:

var a = [
  {name: "Max"},
  {name: "Jhon"},
  {name: "Naton"},
];
var b = [
  {name: "Max"},
  {name: "Naton"},
];

for(let entry of b){
  for(let entry2 of a){
    if(entry2.name == entry.name){
      console.log('includes', entry.name);
    }
  }
}

或:您可以使用对象的字符串版本通过includes()进行检查:

var a = [
  {name: "Max"},
  {name: "Jhon"},
  {name: "Naton"},
];
var b = [
  {name: "Max"},
  {name: "Naton"},
];
var aTemp = a.map(i => JSON.stringify(i));
var bTemp = b.map(i => JSON.stringify(i));
for(let entry of bTemp){
  if(aTemp.includes(entry)){
    console.log('includes', entry);
  }
}

答案 1 :(得分:3)

方法Array.includes()将数组的条目与给定值进行比较。因为您的数组条目是对象,所以它将不匹配。您必须自己遍历数组并进行比较。

Array.some()在数组上循环,如果至少返回true,则返回true。当您要验证某些内容时,此方法很有用。在我们的示例中,我们要验证数组a是否包含b条目。

const a = [{
    name: 'Max',
  },
  {
    name: 'Jhon',
  },
  {
    name: 'Naton',
  },
];

const b = [{
    name: 'Max',
  },
  {
    name: 'Naton',
  },
  {
    name: 'Daddy',
  },
];

console.log(b.map(x => a.some(y => y.name === x.name)));


如果我将其分解:

const a = [{
    name: 'Max',
  },
  {
    name: 'Jhon',
  },
  {
    name: 'Naton',
  },
];

const b = [{
    name: 'Max',
  },
  {
    name: 'Naton',
  },
  {
    name: 'Daddy',
  },
];

// Loop on every entry of the b array
b.forEach((x) => {
  // x here represent one entry
  // first it will worth { name: 'Max' }, then { name: 'Naton' } ...
  // for each value we are going to look at a if we can find a match
  const isThereAMatch = a.some((y) => {
    // y here is worth one entry of the a array
    if (y.name === x.name) return true;

    return false;
  });

  if (isThereAMatch === true) {
    console.log(`We have found ${x.name} in a`);
  } else {
    console.log(`We have not found ${x.name} in a`);
  }
});

答案 2 :(得分:1)

当您使用 Array#includes() method 时,它将始终返回false ,因为它比较的是objects,它们不相等,因为它们不相等不要引用相同的object

您应该比较对象properties而不是整个对象,可以使用 Array#some() method 进行比较,如下所示:

for (let entry of this.b) {
  if (this.b.some(x => x.name === entry.name)) {
    console.log('includes');
  }
}

演示:

A = [{
    name: "Max"
  },
  {
    name: "Jhon"
  },
  {
    name: "Naton"
  },
]

B = [{
    name: "Max"
  },
  {
    name: "Naton"
  },
]

//Filter objects that exists in both arrays
let result = A.filter(el=> B.some(x => x.name === el.name));
console.log(result);