0

I have an array of two objects and I want to check if an array contains an object that I provide it?

I have tried this thing with array.some as shown in the image below:

enter image description here

I know I can do something like:

arr.some(item => item.id === 1)

or

const objectToCompare = { id: 1, firstName: "Vishal", lastName: "Seema" };
arr.some(item => item.id === objectToCompare.id);

But I don't want to do that or compare each property as I want a generic solution when property names are not known.

Can you suggest a way for full object comparison?

Charlie
  • 22,886
  • 11
  • 59
  • 90
Vishal
  • 6,238
  • 10
  • 82
  • 158

2 Answers2

0

A simple solution will be using something like this:

var arr = [{ id: 1, firstName: "Vishal", lastName: "Seema" }, { id: 2, firstName: "FirstName1", lastName: "LastName1" }, { id: 3, firstName: "FirstName2", lastName: "LastName2" }];
var toFind = { id: 1, firstName: "Vishal", lastName: "Seema" };

var matches = arr.filter(obj => { 
                 return Object.keys(toFind).length == Object.keys(obj).length &&
                        Object.keys(toFind).every(key => obj[key] == toFind[key]);
              });
console.log(matches);

This doesn't do a deep check, it only checks the first level.

Titus
  • 22,031
  • 1
  • 23
  • 33
0

All major libraries and frameworks provide dedicated functionalities for object comparison. If it is not for you to do it by iterating the objects in question, use one of the libraries.

Underscore JS isEqual()

JQuery $.fn.equals()

Angular JS angular.equals

There are much more if you google for it.

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • I am using React with ES6. I won't use underscore anymore as es6 has covered most of the functionality and just for 1 function I can't afford to load a library. Other 2 options does not fit in my scenario. – Vishal Jan 13 '18 at 10:21