0

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);
  });
2
  • I don't think that's valid JSON. Maybe you meant Person: {? Also what is personArray? Should we assume it's the array in the JSON object with key person? Commented Jul 20, 2022 at 9:53
  • is it an array like [{name:'',age:''},{name:'',age:''}...] . if so yourmainobj.persons.forEach... Commented Jul 20, 2022 at 9:54

3 Answers 3

1

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);
});

Sign up to request clarification or add additional context in comments.

Comments

0

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);
});

Comments

0

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']

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.