Emu
Emu

Reputation: 5895

Check if array of hashes contains hash

Let's say I have a variable like:

var vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    }
];

var v1 = {
      Name: 'Magenic',
      ID: 'ABC'
     };

When I run the following code to search for v1 in vendors using indexOf it always returns -1

console.log(vendors.indexOf(v1));

Even though v1 exists in vendors array it returns -1. What it the proper way to find the index of an object in array of objects using js?

I can use a loop, but it is costly :(

Upvotes: 1

Views: 3818

Answers (3)

kevin ternet
kevin ternet

Reputation: 4612

This way you can test if an object is contained in an array of objects

var vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    }
];

var v1 = {
      Name: 'Magenic',
      ID: 'ABC'
     };

var result = vendors.findIndex(x => x.ID === v1.ID && x.Name === v1.Name)
console.log(result);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

To check if array contains object you can use some() and then check if each key - value pair exists in some object of array with every(), and this will return true/false as result.

var vendors = [{
  Name: 'Magenic',
  ID: 'ABC'
}, {
  Name: 'Microsoft',
  ID: 'DEF'
}];

var v1 = {
  Name: 'Magenic',
  ID: 'ABC'
};

var result = vendors.some(function(e) {
  return Object.keys(v1).every(function(k) {
    if(e.hasOwnProperty(k)) {
      return e[k] == v1[k]
    }
  })
})

console.log(result)

Upvotes: 1

GG.
GG.

Reputation: 21834

You can use findIndex:

var vendors = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' }];

console.log(vendors.findIndex(v => v.ID === 'ABC')) // 0
console.log(vendors.findIndex(v => v.ID === 'DEF')) // 1

Upvotes: 5

Related Questions