yerassyl
yerassyl

Reputation: 3048

Iterate over json hash in javascript

Json:

{
 "comments":[
    {"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"},
    {"id":2,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/2.json"},{"id":3,"author_name":"Yerassyl","comment_text":"Hello world!","url":"http://localhost:3000/comments/3.json"},
    {"id":4,"author_name":"Yerassyl","comment_text":"hi there","url":"http://localhost:3000/comments/4.json"}
 ]
}

How to iterate over each comment in comments. I want something like that:

//pseudocode
comments.each(key,value){
// do something
}

I tried map, but map is for arrays.

EDIT: If i delete root node 'comments' i can use .map:

var commentNodes = this.props.comments.map(function(comment,index){
      });

Ignore this.props, it is actually React.js.
console.log(this.props.comments) returns my json objects with root node 'comments'

Upvotes: 0

Views: 536

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

Firstly you have to parse your JSON data:

var json = '{
 "comments":[
    {"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"},
{"id":2,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/2.json"},{"id":3,"author_name":"Yerassyl","comment_text":"Hello world!","url":"http://localhost:3000/comments/3.json"},
{"id":4,"author_name":"Yerassyl","comment_text":"hi there","url":"http://localhost:3000/comments/4.json"}
 ]
}';
var data = JSON.parse(json);

And then you can proceed and loop throught comments like this:

data.comments.forEach(function(comment, index) {
    console.log("Comments["+index+"]: "+comment);
});

Note:

Once your JSON is parsed you will get an object including an array of comments so you can easily use all the Array.prototype methods with it including forEach and map.

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78525

Assuming you have already JSON.parsed the string, you can use forEach to iterate. Map is only for returning a new array from your existing values.

this.props.comments.comments.forEach(function(value, index) {
    console.log(value, index);
});

edit: Sounds like this.props.comments is the root object. Hence the accessor above

Upvotes: 1

Evan Knowles
Evan Knowles

Reputation: 7501

Assuming you have

var obj = {
 "comments":[
    {"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"},
    {"id":2,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/2.json"},{"id":3,"author_name":"Yerassyl","comment_text":"Hello world!","url":"http://localhost:3000/comments/3.json"},
    {"id":4,"author_name":"Yerassyl","comment_text":"hi there","url":"http://localhost:3000/comments/4.json"}
 ]
};

You can just do, for example,

obj.comments.map(function (comment) {
    console.log(comment);
});

Upvotes: 1

Related Questions