简体   繁体   中英

Retrieve Value Using Key in Associative Array

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 .

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);

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'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM