1

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 ?

Lazyexpert
3,1741 gold badge23 silver badges33 bronze badges
asked Sep 18, 2017 at 14:40
2
  • show the code, you've already tried. Commented Sep 18, 2017 at 14:43
  • for(var jsondata in body){ console.log(jsondata); } This returns 0,1,2...as output Commented Sep 18, 2017 at 14:44

3 Answers 3

1

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);
 }
answered Sep 18, 2017 at 14:51
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Sep 18, 2017 at 14:46

Comments

0

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

answered Sep 18, 2017 at 14:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.