albuvee albuvee - 6 months ago 9
Javascript Question

Get object where the value of key is equal to array value

How can I get the corresponding object from data where the value (for example

888
) of a key (for example
id
) is equal to the value of a looping variable (i.e.
id[i] == 888
)?

My data looks like:

{
"players": {
"player6": {
"id": "777",
"name": "Barak Obama",
"trck": "obama",
"img": "dev/obama.jpg",
"img2x": "dev/obama_2x.jpg"
},
"player23": {
"id": "888",
"name": "George Bush",
"trck": "bush",
"img": "dev/bush.jpg",
"img2x": "dev/bush_2x.jpg"
},
"player87": {
"id": "999",
"name": "Bill Clinton",
"trck": "clinton",
"img": "dev/clinton.jpg",
"img2x": "dev/clinton_2x.jpg"
}
},
"coaches": {…},
"manager": {…},
"staff": {…}
}


To start with, I have an array wich consists of one or multiple numbers (for example
[888,999]
). They do represent the IDs of selected players (not necessarily all of them, just one or multiple ones).

Now, how can I get all the corresponding data of the associated player (like name, trck, img, etc.) where the key
id
equals the number from an array (looping) in the value?


  • loop through my array
    [888,999]

  • get the data from all players where
    id == 888
    first, and then
    999

  • use this data (name, id, trck, img, etc.) to add some HTML markup with those values to the page



Update: I'm using jQuery.

Answer

Simple enough (and exactly following your description):

var ids = [888,999];

$.each(ids, function (i, id) {
    $.each(data.players, function (key, player) {
        if (player.id == id) {
            // add player.name, .id, .trck, .img, etc to page

            return false; // break the execution of $.each();
        }
    });
});

Note that player.id == id makes use of the automatic type conversion in JS, so it's very much intentional that it is not a strict comparison (===).

Comments