What is the context in which you are using this array?
Maybe the problem is not in how to retrieve the values, but in the data structure you are building.
Your data structure needs to be planned to avoid future problems.
I recommend using a more generic structure, eg:
var arr = [
{ name: 'David', id: '1'},
{ name: 'Camilla', id: '2'},
{ name: 'Sadat', id: '3'},
{ name: 'Vanuza', id: '4'},
{ name: 'Diego', id: '5'}
];
This way you will be able to iterate better with your data array when you need it. In this case, for example, you could use a utility library such as lodash (method _.find
) that has several methods that help you manipulate data.
EDITED:
If you still prefer to leave the data structure the way it is or can not change it, you can create a function to access the value:
function getValueByKey (collection, key) {
var value;
collection.map(function (item) {
if (key in item) value = item[key];
})
return value;
}
link