我有一组对象,我使用.includes()
函数。我正在使用数组中的对象搜索此数组(对象相同)。然而,似乎并不匹配。我在this fiddle中复制了这个问题。代码也在下面。那么检查数组是否包含对象的正确方法是什么?
let list1 = [{
name: "object1"
},
{
name: "object2"
},
{
name: "object3"
},
{
name: "object4"
}
]
if (list1.includes({
name: "object1"
})) {
document.write('contains')
} else {
document.write('doesnt')
}

答案 0 :(得分:4)
您无法直接比较对象,但使用this method,您可以将它们与JSON.stringify进行比较。
let list1 = [{
name: "object1"
},
{
name: "object2"
},
{
name: "object3"
},
{
name: "object4"
}
]
var contains = list1.some(elem =>{
return JSON.stringify({name: "object1"}) === JSON.stringify(elem);
});
if (contains) {
document.write('contains')
} else {
document.write('doesnt')
}
答案 1 :(得分:2)
您可以尝试以下
let list1 = [{name:"object1"},{name:"object2"},{name:"object3"},{name:"object4"}]
if (list1.some(({name}) => name === "object1")) {
document.write('contains')
} else {
document.write('doesnt')
}