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 ?
-
show the code, you've already tried.Lazyexpert– Lazyexpert2017年09月18日 14:43:40 +00:00Commented Sep 18, 2017 at 14:43
-
for(var jsondata in body){ console.log(jsondata); } This returns 0,1,2...as outputUser09111993– User091119932017年09月18日 14:44:55 +00:00Commented Sep 18, 2017 at 14:44
3 Answers 3
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);
}
Comments
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.
Comments
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){}