Javascript's .includes function not working co

2020-04-10 01:32发布

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')
}

2条回答
我只想做你的唯一
2楼-- · 2020-04-10 01:49

You can try following

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


if (list1.some(({name}) => name === "object1")) {
  document.write('contains')
} else {
  document.write('doesnt')
}

查看更多
够拽才男人
3楼-- · 2020-04-10 02:06

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')
}

查看更多
登录 后发表回答