albuvee albuvee - 2 years ago 89
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

) of a key (for example
) 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
). 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
equals the number from an array (looping) in the value?

  • loop through my array

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

  • 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 Source

Simple enough (and exactly following your description):

var ids = [888,999];

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download