-9

I have created an object like this.

myObj =  {
   "name":"John",
   "age":30,
   "cars": [
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
   ]
   }

I can easily read name and age but I want to read the content (key values) under object "cars". I want to put key values in the drop-down so that if select any key from cars then I will get respective values. Thank you!

Ashish
  • 85
  • 1
  • 2
  • 14
  • 4
    `myObj.cars.car1`, `myObj.cars.car2` ... Also, just FYI that's an object literal, not JSON. – Rory McCrossan Dec 15 '17 at 12:03
  • It would be easier if you made the cars object an array. You'd get "cars": ["Ford", "BMW", "Fiat"]. – Mizzcoollizz Dec 15 '17 at 12:06
  • Do you want to read the values or the keys? What's your expected list of values? "car1,car2,car3" ? What you've described is: ` – freedomn-m Dec 15 '17 at 12:06

2 Answers2

1

Simply do it by myObj.cars.car1 , myObj.cars.car2 and , myObj.cars.car3 to get directly or loop as below example

var myObj = {
  "name": "John",
  "age": 30,
  "cars": {
    "car1": "Ford",
    "car2": "BMW",
    "car3": "Fiat"
  }
};

for (let i in myObj) {
  if (typeof myObj[i] == 'object') {
    for (let j in myObj[i]) {
      console.log(j, myObj[i][j]);
    }
  } else {
    console.log(i, myObj[i]);
  }
}
freelancer
  • 1,174
  • 5
  • 12
-1

Use dot operator , by which you can access the properties

myObj = {
    "name":"John",
    "age":30,
    "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Fiat"
    }
 }
 console.log(myObj.cars.car1);
  console.log(myObj.cars.car2);
   console.log(myObj.cars.car3);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396