User09111993
User09111993

Reputation: 176

How can i loop through json data?

I am trying to learn node.js but at some point i got stuck. This is my json input : [ { "FIELD1": "name", "FIELD2": "id"}, { "FIELD1": "abc", "FIELD2": "12"}]

How can i loop through this,i tried 'for' but it didn't work. can any one help ?

Upvotes: 1

Views: 89

Answers (3)

Alejandro Camba
Alejandro Camba

Reputation: 988

You're trying to loop over an array of json objects, so you could just

  for(let i= 0; i < object.length; i++){
        //access your object fields
        console.log(object[i].FIELD1);
        console.log(object[i].FIELD2);
  }

Upvotes: 1

Lazyexpert
Lazyexpert

Reputation: 3154

Basically you can use 3 opportunities here:

  • Array.forEach (shown below)
  • usual for loop ( for(let t = 0; t < data.length; t++) { ... } )
  • ES7 for of loop (for(const el of data) { ... })

Assuming you have such data:

const data = [ { "FIELD1": "name", "FIELD2": "id"}, { "FIELD1": "abc", "FIELD2": "12"}];

You can loop through it:

data.forEach(el => console.log(el));

The one you've tried: for(let prop in obj) is used to iterate through objects, not arrays.

Upvotes: 0

Luple
Luple

Reputation: 491

well, first of all you are looping over an array. That you can do.

For looping over a json, you can either get the keys. I believe .keys().

I also believe you can do for(var x in json){}

Upvotes: 0

Related Questions