0

I have a json file converted into a js object

var factory = {
  city: "turin",
  street: "corso unione sovietica",
  nAddres: 74,
  operative: true,
  models: ["toyota", "chevrolet", "ford", "subaru", "honda"],
  workspace: {
    offices: 12,
    minsOfPause: 15,
  },
  cars: {
    toyota: {
      id: 1,
      numberPlate: "S4IIPLE",
      broken: false,
      insurance: null,
      previousOwners: ["Mark", "Sebastian", "Carlos"],
      infos: {
        parketAt: "425 2nd Street",
        city: "San Francisco",
        state: "CA",
        postalCode: 94107,
      },
    },
    chevrolet: {
      id: 2,
      numberPlate: "S2IALR",
      broken: true,
      insurance: null,
      previousOwners: ["Robert", "Mark"],
      infos: {
        parketAt: "711-2880 Nulla St",
        city: "Mankato",
        state: "MS",
        postalCode: 96522,
      },
    },
  },
};
var json = JSON.stringify(factory);
json = JSON.parse(json);

I have to display the data in a ul li list in an HTML file but when I try to iterate the objects with

for(var a in json){
  console.log(a);  
}

the console says that the object is not iterable and with

for(var a of json){
  console.log(a);

the console doesn't display the value pls help

Slom
  • 61
  • 5
  • A plain object is not iteratable. Use `Object.keys()` or something like ` for (const [key, value] of Object.entries(object1)) { console.log(`${key}: ${value}`); }` this – Marc Oct 10 '20 at 17:36
  • 2
    This is an often-asked question. You are trying to iterate through an object so you will need `Object.entries`. Answer to your question [here](https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object) – Ray Toal Oct 10 '20 at 17:36
  • 2
    First option (`for...in`) should work for iterating over the **keys** of the object ([more info](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Sentencias/for...in)). – jeojavi Oct 10 '20 at 17:39
  • Ty for the responses! I got everything but the first comment. What is this ${key}: ${value}, or better, what does the $ means – Slom Oct 10 '20 at 17:47

1 Answers1

1

A for...of loop is used to loop through an array.

For an object, we should use for...in loop.

Here, it should be :

for (let a in json){
  console.log(a);
}
Agneesh Bose
  • 211
  • 3
  • 4