-3

this is my array,

var myArray =[{ a: 'b'}, { b: 'b'}, { c: 'b'},{ g: 'b'}];

But when i used indexOf, its not working,

var myArray =[{ a: 'b'}, { b: 'b'}, { c: 'b'},{ g: 'b'}]
var myObj = { g: 'b'};

var isInArray = myArray.indexOf(myObj);

console.log(isInArray)

Whats the problem ?

khristy_01
  • 37
  • 5

4 Answers4

0

Array.indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

In your case, myObj is not the same as the similar object contained in the array, hence it cannot be found.

For further details, please take a look at this answer.

uminder
  • 23,831
  • 5
  • 37
  • 72
0

You need to iterate the array and the entried of the wanted object and check if key and value match.

const
    array =[{ a: 'b' }, { b: 'b' }, { c: 'b' }, { g: 'b' }],
    object = { g: 'b' },
    isInArray = array.some(o =>
        Object.entries(object).every(([k, v]) => k in o && o[k] === v)
    );

console.log(isInArray);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

If you want to find out if a particular value is in an Object array I would just write it like this

var myArray = [{
  a: 'b'
}, {
  b: 'b'
}, {
  c: 'b'
}, {
  g: 'b'
}]
var myObj = { g: 'b' };

for (i in myArray) {
  if (myArray[i] == myObj) {
    console.log('Value exists')
  }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
swift gaming
  • 142
  • 4
-1

Two way to resolve

// Example #1
// Add " on each items
var myArray =["{ a: 'b'}", "{ b: 'b'}", "{ c: 'b'}","{ g: 'b'}"]
var myObj = "{ g: 'b'}";

var isInArray = myArray.indexOf(myObj);

console.log(isInArray)


/*
* OR Try this method
*/

// Example #2
var myArray2 =[{ a: 'b'}, { b: 'b'}, { c: 'b'},{ g: 'b'}]

var isInArray2 = myArray2.map(function(e) {
                    return e.g; // <-- 'g:' from array
                  }).indexOf('b'); // <-- 'b' from array

console.log(isInArray2)
GMKHussain
  • 3,342
  • 1
  • 21
  • 19