Home > Back-end >  access Object value inside another Obejct
access Object value inside another Obejct

Time:11-14

I have object inside the object which there is another object inside that how i can access all my value at once and iteration them with loop i tried the block of code blow and did work for name1

let x = "";
const myObj = {
    name: "John",
    age: 30,
    cars: {
        car1: { name1: "Ford", model: "mostang" },
        car2: { name1: "BMW", model: "x33" },
        car3: { name1: "benz", model: "2000s" },
    },
};

for (let i in myObj.cars) {
    x  = "<h2>"   myObj.cars[i].name1   "</h2>";
}

document.getElementById("demo").innerHTML = x;
<div id="demo"> </div>

CodePudding user response:

You can use Object.keys or Object.values and for of to achieve this.

let x = "";
const myObj = {
    name: "John",
    age: 30,
    cars: {
        car1: { name1: "Ford", model: "mostang" },
        car2: { name1: "BMW", model: "x33" },
        car3: { name1: "benz", model: "2000s" },
    },
};
// using Object.keys
for (let i of Object.keys(myObj.cars)) {
    x  = "<h2>"   myObj.cars[i].name1   "</h2>";
}

// using Object.values
for (let value of Object.values(myObj.cars)) {
    x  = "<h2>"   value.name1   "</h2>";
}

document.getElementById("demo").innerHTML = x;

<div id="demo"> </div>

CodePudding user response:

by adding x = myObj.cars[i].model after x = "<h2>" myObj.cars[i].name1 "</h2>"; you can access model key too

let x = "";
const myObj = {
  name: "John",
  age: 30,
  cars: {
    car1:{name1:"Ford", model:"mostang"},
    car2:{name1:"BMW", model:"x33"},
    car3:{name1:"benz", model:"2000s"}
  }
}

for (let i in myObj.cars) {
  x  = "<h2>"   myObj.cars[i].name1   "</h2>";
  x  =  myObj.cars[i].model 
}

document.getElementById("demo").innerHTML = x;
<div id="demo"></div>

  • Related