繁体   English   中英

遍历JavaScript中的JSON哈希

[英]Iterate over json hash in javascript

杰森:

{
 "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);
});

假设您已经有了JSON.parse字符串,则可以使用forEach进行迭代。 Map仅用于从现有值返回新数组。

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

编辑:听起来像this.props.comments是根对象。 因此,上面的访问器

首先,您必须解析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方法一起使用,包括forEachmap

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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