javascriptnested-object

loop through nested object javascript


I am trying to loop through a following nested object and get an output as below:

const preference = {
    "ethnicity": {
        "value": "Newar",
        "rank": 1
    },
    "occupation": {
        "value": "Banker",
        "rank": 2
    }
}

I tried following:

let preferenceRank = {};
preference.map(pref => {
  preferenceRank[pref.rank] = pref; 
});

console.log(preferenceRank);

I get this error:

"TypeError: preference.map is not a function"...

Output required:

{
  1: "ethnicity",
  2: "occupation",
}

Solution

  • You can use Object.entries to get keys and values at once (as array of arrays [key, value]):

    const preference = {
        "ethnicity": {
            "value": "Gurung",
            "rank": 1
        },
        "occupation": {
            "value": "Banker",
            "rank": 2
        }
    }
    
    const preferenceRank = {}
    for (const [key, { rank }] of Object.entries(preference)) {
        preferenceRank[rank] = key
    }
    
    console.log(preferenceRank)

    (By the way, in your code it doesn't make any sense to use map there, since you are not mapping the array to anything, and you ignore the return value of map. You probably wanted forEach instead or, as I used now, a for loop.)


    2021 Update

    There is now an easier way widely available, using Object.fromEntries, which does the opposite of Object.entries, thereby allowing us to express the whole thing as a mapping operation:

    const preferenceRank = Object.fromEntries(
      Object.entries(preference).map(([key, { rank }]) => [rank, key])
    )