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"}
]
}
如何在评论中迭代每条评论。我想要这样的东西:
//pseudocode
comments.each(key,value){
// do something
}
我试过了地图,但地图是用于数组的。
编辑: 如果我删除根节点'comments'我可以使用.map:
var commentNodes = this.props.comments.map(function(comment,index){
});
忽略this.props,它实际上是React.js console.log(this.props.comments)返回带有根节点'comments'的json对象
答案 0 :(得分:1)
假设你有
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);
});
答案 1 :(得分:1)
假设您已经class Test:
def __init__(self, val):
self.a = val
T = Test (10)
T1 = Test(20)
print str(T.a) + '__' + str(T1.a)
了字符串,可以使用forEach进行迭代。 Map仅用于从现有值返回新数组。
JSON.parse
编辑:听起来像this.props.comments.comments.forEach(function(value, index) {
console.log(value, index);
});
是根对象。因此上面的访问者
答案 2 :(得分:1)
首先,您必须解析您的JSON数据:
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);
然后你可以继续循环并完成这样的评论:
data.comments.forEach(function(comment, index) {
console.log("Comments["+index+"]: "+comment);
});
注意:强>
解析完JSON后,您将获得一个包含一系列注释的对象,以便您可以轻松地使用所有 Array.prototype 方法,包括forEach
和{{1 }}