What is the context in which you are using this array?
Maybe the problem is not how to recover the values, but in the data structure that is building.
Your data structure needs to be planned to avoid future problems.
I recommend using a more generic structure, example:
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 matrix when you need it. In this case for example you could use a utility library like lodash (method _.find
) that has various methods that helps you manipulate data.
EDITED:
If you still prefer to leave the data structure the way it is or can’t 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;
}
https://jsfiddle.net/t0kt8vkn/
Do you want, for each element of the array, to access the key? Or is it for a specific element? These elements only have a key/value pair?
– mgibsonbr