Javascript’s .includes function not working correctly with array of objects [duplicate]

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

Leave a Comment