[英]Check if object from one array is included inside another array of objects
[英]How to check if all objects of array are included another array?
我试图检查对象array A
包含来自B
objects
。
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');
}
}
但是我对includes
false
。
您必须使用另一个循环,然后检查属性名称:
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); } }
方法Array.includes()
将数组的条目与给定值进行比较。 因为您的数组条目是对象,所以它不匹配。 你必须自己循环数组并进行比较。
Array.some()
在数组上循环,如果返回true至少为1,则返回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`); } });
当您使用Array#includes()
方法时 ,它将始终返回false
因为它正在比较不相等的objects
,因为它们没有引用同一个object
。
您应该比较对象properties
而不是整个对象,您可以使用Array#some()
方法来执行此操作,如下所示:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.