How can I get the index of an object by its property in JavaScript?
arrays, javascript, object
Solution
As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
With this, not only can you find which one contains 'John', but you can find which contains the token '312312':
findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1
The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().
Problem
For example, I have: ``` var Data = [ { id_list: 1, name: 'Nick', token: '312312' }, { id_list: 2, name: 'John', token: '123123' }, ] ``` Then, I want to sort/reverse this object by `name`, for example. And then I want to get something like this: ``` var Data = [ { id_list: 2, name: 'John', token: '123123' }, { id_list: 1, name: 'Nick', token: '312312' }, ] ``` And now I want to know the index of the object with property `name='John'` to get the value of the property token. How do I solve the problem?