检查对象数组是否包含另一个对象

时间:2020-08-10 08:08:55

标签: javascript

我有此代码:

const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
console.log(arr.includes({name:"Bill", age:11}))

在这里,我要检查数组是否包含{name:"Bill", age:11}
为什么我会虚假?以及如何使用包含进行此项检查?

2 个答案:

答案 0 :(得分:3)

includes()方法按引用而不是按值比较对象。在您的情况下,尽管三个对象具有相同的属性和相同的值,但它们具有三个不同的引用。

const bill = { name: 'Bill', age: 11 }
const arr = [bill, { name: 'Jane', age: 18 }]

arr.includes(bill) // true (same reference)
arr.includes({ name: 'Bill', age: 11 }) // false (different reference)

如果要按值查找对象,可以使用find()方法并传递一个过滤器函数,该函数检查对象的每个属性是否符合您的条件。

const arr = [{name:"Bill", age:11}, {name:"Jane", age:18}]
const exists = Boolean(arr.find(x => x.name === 'Bill' && x.age === 11))

// or even simpler using the `some()` method
const exists = arr.some(x => x.name === 'Bill' && x.age === 11)

答案 1 :(得分:1)

您可以为此创建自定义数组原型方法,例如includesObj

const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]

Array.prototype.includesObj = function(obj) {
   for(let i = 0; i < this.length; i++) {
      if(JSON.stringify(this[i], Object.keys(this[i]).sort()) === JSON.stringify(obj, Object.keys(obj).sort())) return true;
   }
   return false;
}

console.log(arr.includesObj({name: "Bill", age: 11}))
console.log(arr.includesObj({age: 11, name: "Bill"}))
console.log(arr.includesObj({name: "Bob", age: 11}))

相关问题