Reputation: 16191
I have an array into which I insert a load of values along with their corresponding keys. They are inserted fine as I can see them all in the array when I do a console.log
.
The issue is, I can't seem to retrieve the values from the array using their respective keys.
Here is my code.
var personArray = [];
personArray.push({
key: person.id,
value:person
});
var personID = person.id;
console.log(personArray.personID);
I have also tried console.log(personArray[personID];
but this does not work either.
The value I get in my console is undefined
.
Upvotes: 1
Views: 170
Reputation: 12683
You can use dictionary format as suggested by @freakish, Or use the filter function to find the required object.
For example:
var personArray = [];
var person = {id: 'aki', value:'Akhil'}
personArray.push({
key: person.id,
value:person
});
personArray.filter(function(item){
return item.key == 'aki'
});
Upvotes: 0
Reputation: 56467
What you are doing is that you push dictionaries into the array. If person.id
is unique, then you can do this:
var personDict = {}
personDict[person.id] = person
and then personDict[personID]
will work. If you want to keep your structure, then you have to search inside the array for it:
var personArray = [];
personArray.push({
key: person.id,
value:person
});
var personID = person.id;
var search = function(id) {
var l = personArray.length;
for (var i = 0; i < l; i++) {
var p = personArray[i];
if (p.key === id) {
return p.value;
}
}
return null;
};
search(personID);
Upvotes: 4