javascript - Check if array of hashes contains hash - Stack Overflow

Let's say I have a variable like:var vendors = [{Name: 'Magenic',ID: 'ABC'},{N

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 :(

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 :(

Share Improve this question edited Dec 16, 2016 at 6:36 GG. 21.9k14 gold badges92 silver badges133 bronze badges asked Dec 13, 2016 at 17:36 EmuEmu 5,9153 gold badges35 silver badges52 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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

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)

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745548392a4632448.html

相关推荐

  • javascript - Check if array of hashes contains hash - Stack Overflow

    Let's say I have a variable like:var vendors = [{Name: 'Magenic',ID: 'ABC'},{N

    11小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信