0

I have a JSON object which looks like this:

[
  objA={
    "name" : "Joe",
    "age" : 22,
    "hobbies" : ["Skiing", "Running"]
  },
  objB={
    "name" : "Rebecca",
    "age" : 34,
    "hobbies" : ["Football", "Archery"]
  }
]

I'm having trouble writing a for loop which will print the name, age and hobbies of each object.

I'm getting the JSON object from another file using:

$.getJSON("data/hobbies.json", test);

Where test is the function which the data will be used in.

How can I achieve this?

  • What would be the desired output ? If you just want to output everything in a JSON format, use [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)Also, this is a JavaScript object, not a JSON object (https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Seblor Oct 08 '19 at 09:05
  • Just to print in the format name: *name*, age: *age*, hobbies: *list of hobbies* @Seblor –  Oct 08 '19 at 09:09
  • If you don't care about formatting, then `JSON.stringify` should be enough for you. – Seblor Oct 08 '19 at 09:16

2 Answers2

0
    let object = [
       objA={
        "name" : "Joe",
        "age" : 22,
        "hobbies" : ["Skiing", "Running"]
      },
      objB={
        "name" : "Rebecca",
        "age" : 34,
        "hobbies" : ["Football", "Archery"]
      }
    ]

    object.forEach((data)=>{
        console.log(data)
        //console.log(data.name)
        //console.log(data.age)
        //console.log(data.hobbies)
    })

Copy and paste the code here to try. https://repl.it/languages/javascript

OUTPUT:

{ name: 'Joe', age: 22, hobbies: [ 'Skiing', 'Running' ] } { name: 'Rebecca', age: 34, hobbies: [ 'Football', 'Archery' ] }

0
var a = [
    objA={
        "name" : "Joe",
        "age" : 22,
        "hobbies" : ["Skiing", "Running"]
    },
    objB={
        "name" : "Rebecca",
        "age" : 34,
        "hobbies" : ["Football", "Archery"]
    }
];
a.forEach(function (data) {
    console.log('name:', data.name);
    console.log('age:', data.age);
    console.log('hobbies:', data.hobbies);
});

result:

  • name: Joe age: 22 hobbies: ["Skiing", "Running"]
  • name: Rebecca age: 34 hobbies: ["Football", "Archery"]
Ricky sharma
  • 701
  • 9
  • 21