简体   繁体   中英

How to iterate over json with root node in JavaScript

I have a json with root node:

 { "comments": [ {"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"} ] }

and I want to go through each object. This is what i try:

 var commentNodes = this.props.comments.map(function(comment,index){ // do something over each object ); });

But it is not working:

 Uncaught TypeError: this.props.comments.map is not a function

You can just iterate over it with a for loop like this:

data = {
    "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"
        }
    ]
}

for (var i = 0; i < data.comments.length; i++) {
    var comment = data.comments[i];

    // do something with the comment
    // console.log(comment.id);
    // console.log(comment.url);
}

Or if you want to get all comment authors for example, you could do this:

var authors = data.comments.map(function(comment) {
    return comment.author_name;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM