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

4
  • 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 Commented Oct 10, 2020 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 Commented Oct 10, 2020 at 17:36
  • 2
    First option (for...in) should work for iterating over the keys of the object (more info). Commented Oct 10, 2020 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 Commented Oct 10, 2020 at 17:47

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.