杰森:
{
"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"}
]
}
如何遍历注释中的每个注释。我想要这样的东西:
//pseudocode
comments.each(key,value){
// do something
}
我尝试了map,但是map是用于数组的。
编辑:
如果删除根节点“注释”,则可以使用.map:
var commentNodes = this.props.comments.map(function(comment,index){
});
忽略this.props,实际上是React.js。
console.log(this.props.comments)返回带有根节点“ comments”的json对象
最佳答案
假设你有
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"}
]
};
例如,您可以这样做
obj.comments.map(function (comment) {
console.log(comment);
});
关于javascript - 遍历JavaScript中的JSON哈希,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31155024/