Search code examples
javascriptoopobjectfor-in-loopnested-object

How to show js object name and its all property value?


I have object like this

var savedColor = {
    "plat1" : {
        "background" : "rgb(0,0,0)",
        "text" : "rgb(255,255,255)"
    },
    "plat2" : {
        "background" : "rgb(0,50,50)"
        "text" : "rgb(0,0,0)"
    }
}

I want to show the output like this:

plate1
rgb(0,0,0)
rgb(255,255,255)
plate2
rgb(0,50,50)
rgb(0,0,0)

I tried this code:

for(var x in savedColor){
    console.log(savedColor[x]);
    for(var y in savedColor[x]){
        console.log(savedColor[y]);
    }
}

But the output is not showing like what i want.The output:

[Object object]
undefined
undefined
[Object object]
undefined
undefined

How can i show the output like I told above?


Solution

  • Use Object.entries to get the outer key (which you can print) and the object, and then iterate over the Object.values of the inner object and print that:

    var savedColor = {
        "plat1" : {
            "background" : "rgb(0,0,0)",
            "text" : "rgb(255,255,255)"
        },
        "plat2" : {
            "background" : "rgb(0,50,50)",
            "text" : "rgb(0,0,0)"
        }
    }
    for (const [key, obj] of Object.entries(savedColor)) {
      console.log(key);
      for (const value of Object.values(obj)) {
        console.log(value);
      }
    }