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 badges3 Answers
Reset to default 5You 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
评论列表(0条)