Reputation: 176
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
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
Reputation: 3154
Basically you can use 3 opportunities here:
for(let t = 0; t < data.length; t++) { ... }
)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
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