我有一个带有根节点的json:
{
"comments":
[
{"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"}
]
}

我希望浏览每个对象。 这是我尝试的:
var commentNodes = this.props.comments.map(function(comment,index){
// do something over each object
);
});

但它不起作用:
Uncaught TypeError: this.props.comments.map is not a function

答案 0 :(得分:1)
你可以用这样的for循环迭代它:
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);
}
或者,如果您想以所有评论作者为例,您可以这样做:
var authors = data.comments.map(function(comment) {
return comment.author_name;
});