1

I have invoque array Object in Object JSON but I invoque last index

var myObj, x, i, y;
myObj = {
  "name": "John",
  "age": 30,
  "cars": [{
    "n": "Ford",
    "a": "BMW",
    "c": "Fiat"
  }, {
    "n": "test",
    "a": "BMWwww",
    "c": "Fiattt"
  }]
};
x = myObj.cars[0]["n"];
for (y in myObj.cars) {
  document.getElementById("demo").innerHTML = myObj.cars[y].n;

}
<p>Access an array value of a JSON object:</p>

<p id="demo"></p>

but I have display

Access an array value of a JSON object: test

Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
devit2017
  • 297
  • 2
  • 5
  • 14

1 Answers1

0

You are overwriting the value of innerHTML. You could add the value and a line break tag.

Then I suggest to use a simple for loop with an index variable to use. You might habe a looke here: JavaScript Loops: for…in vs for

var myObj = { name: "John", age: 30, cars: [{ n: "Ford", a: "BMW", c: "Fiat" }, { n: "test", a: "BMWwww", c: "Fiattt" }] },
    i;

for (i = 0; i < myObj.cars.length; i++) {
    document.getElementById("demo").innerHTML += myObj.cars[i].n + '<br>';
}
<p>Access an array value of a JSON object:</p>
<p id="demo"></p>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392