Home > OS >  How to loop through a JSON like this with javascript?
How to loop through a JSON like this with javascript?

Time:07-20

I want to loop through a JSON like this using javascript.

{
    persons: [
      Person {
        name: 'Herbert',
        age: 70
      },
      Person {
        name: 'Peter',
        age: 67
      }
    ]
  }

My first approach was something like this, but this is not working somehow :(

  personArray.forEach((person) => {
    console.log(person.name);
  });

CodePudding user response:

You may use this to get name:

let personArray = {
    persons: [
      {
        name: 'Herbert',
        age: 70
      },
      {
        name: 'Peter',
        age: 67
      }
    ]
}

personArray.persons.map(ele => ele.name) // ['Herbert', 'Peter']

CodePudding user response:

Your json looks invalid. If I understood you correctly, you can do the following:

let json = '{"persons":[{"name":"Herbert","age":70},{"name":"Peter","age":67}]}'
let personArray = JSON.parse(json)

personArray.persons.forEach((person) => {
  console.log(person.name);
});

or, if it is a real javascript object, do the following:


let personArray = {
    persons: [
      {
        name: 'Herbert',
        age: 70
      },
      {
        name: 'Peter',
        age: 67
      }
    ]
}



personArray.persons.forEach((person) => {
  console.log(person.name);
});

CodePudding user response:

JSON does not have forEach, you need to do like this:

let personArray = {
    persons: [
    {
        name: 'Herbert',
        age: 70
    },
    {
        name: 'Peter',
        age: 67
    }
  ]
}
Object.keys(personArray.persons).forEach((key) => {
    console.log(personArray.persons[key].name);
});

  • Related