0

Say I have an array of objects arr = []. Inside arr there are many objects, all of the same format, say.

arr = [
  {
    "a": "asdf",
    "b": {
      "a": 2,
      "b": 1,
      "c": 4
    },
    "c": {
      "a": 0,
      "b": 1
    }
  },
  {
    "a": "xswh",
    "b": {
      "a": 4,
      "b": null,
      "c": 8
    },
    "c": {
      "a": 6,
      "b": 5
    }
  }
]

If I have a variable that is an object of the same shape:

obj1 = {
    "a": "asdf",
    "b": {
      "a": 2,
      "b": 1,
      "c": 4
    },
    "c": {
      "a": 0,
      "b": 1
    }
  }

How can I quickly check to see if this object obj1 is inside the array? (meaning, if inside the array there is an object with the exact same parameters and values.

I tried arr.includes(obj1) but it didn't seem to work.

Bandolero
  • 55
  • 1
  • 9

2 Answers2

0

You could use the findIndex function and do something like:

arr.findIndex(item => JSON.stringify(item) === JSON.stringify(obj1));
J. Pichardo
  • 3,077
  • 21
  • 37
0

Solution using - Lodash

You can use find on the collection (array) to find match for particular object value using isEqual which will perform deep comparison for you (in this case properties of the object).

_.find(arr, (v) => { 
   return _.isEqual(v, obj1);
});

find - 'Find' documentation
isEqual - 'isEqual' documentation

Code.Decode
  • 3,736
  • 4
  • 25
  • 32