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 :(
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.