Reputation: 29877
Is it possible to locate a member field within an object literal that is part of an array of items without looping through the entire array? For example:
let items = [
{
id: "abc",
name: "john"
},
{
id: "def",
name: "steve"
},
{
id: "ghi"
name: "bob"
}
]
If I want to reference the array element where name equals steve
, is there a way to obtain it but without iterating through all the items and checking the name member?
Upvotes: 0
Views: 163
Reputation: 68665
Without explicitly looping you can use Array#find function to get the object from the array. But anyway you need to compare on some condition to get the desired one. And if you don't know the index of the item, you need to loop over the array. Instead of explicitly looping you can use built in methods.
let items = [
{
id: "abc",
name: "john"
},
{
id: "def",
name: "steve"
},
{
id: "ghi",
name: "bob"
}
];
const obj = items.find(item => item.name === 'steve');
console.log(obj);
Upvotes: 4
Reputation: 192016
If you frequently need to get objects by name from the array, you can create a map of name -> object (one time iteration), and then use the map to get the objects:
const items = [
{
id: "abc",
name: "john"
},
{
id: "def",
name: "steve"
},
{
id: "ghi",
name: "bob"
}
];
const itemsMap = items.reduce((m, o) => m.set(o.name, o), new Map());
console.log(itemsMap.get('steve'));
console.log(itemsMap.get('bob'));
Upvotes: 0
Reputation: 318252
yes. I want something like a simple method that given just the name returns the index
Array.findIndex
does that, but it still iterates
let items = [
{
id: "abc",
name: "john"
},
{
id: "def",
name: "steve"
},
{
id: "ghi",
name: "bob"
}
]
var index = items.findIndex( item => item.name === 'steve' );
console.log(index)
Upvotes: 0