【问题标题】:How to iterate over json with root node in JavaScript如何在 JavaScript 中使用根节点迭代 json
【发布时间】:2015-06-30 05:31:26
【问题描述】:

我有一个带有根节点的 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

【问题讨论】:

  • 你是如何定义变量this.props的?
  • @TaoP.R.,忘了说,这其实是 React。
  • 映射用于数组而非对象。

标签: javascript json reactjs


【解决方案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;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 2018-07-30
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多