Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')
}
like image 853
Harvey Lewis Avatar asked May 16 '18 12:05

Harvey Lewis


People also ask

How do you check if an array of objects contains an object JavaScript?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false. Example: html.

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


2 Answers

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')
}
like image 91
Renzo Calla Avatar answered Oct 22 '22 17:10

Renzo Calla


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')
}
like image 6
Nikhil Aggarwal Avatar answered Oct 22 '22 16:10

Nikhil Aggarwal