Javascript的.includes函数与对象数组无法正常工作 [英] Javascript's .includes function not working correctly with array of objects

查看:94
本文介绍了Javascript的.includes函数与对象数组无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我正在使用 .includes()函数。我正在使用数组中的对象搜索此数组(对象相同)。但是似乎没有匹配。我已经在这个小提琴中复制了这个问题。代码也在下面。那么检查数组是否包含对象的正确方法是什么?

I have an array of objects which I'm using the .includes() function. I'm searching this array with an object that is in the array (Objects are identical). However there doesn't appear to be a match. I have replicated the problem in this fiddle. The code is also below. So what is the correct way to check if an array contains am object?

let list1 = [{
    name: "object1"
  },
  {
    name: "object2"
  },
  {
    name: "object3"
  },
  {
    name: "object4"
  }
]


if (list1.includes({
    name: "object1"
  })) {
  document.write('contains')
} else {
  document.write('doesnt')
}

推荐答案

您无法直接比较对象,但使用此方法,您可以将它们与JSON.stringify进行比较。

You can't compare objects directly, but using this method , you can compare them with 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')
}

这篇关于Javascript的.includes函数与对象数组无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆