1

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.

asked Aug 30, 2013 at 5:39

2 Answers 2

4

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);
answered Aug 30, 2013 at 5:43
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. New to javascript so still struggling with syntax
0

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'
});
answered Aug 30, 2013 at 5:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.