gpt4 book ai didi

javascript - 在 javascript 中迭代 json 哈希

转载 作者:行者123 更新时间:2023-11-28 19:08:41 25 4
gpt4 key购买 nike

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
}

我尝试了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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com