2015-07-01 110 views
0

JSON:遍歷JSON哈希在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:

var commentNodes = this.props.comments.map(function(comment,index){ 
     }); 

忽略this.props,它實際上是React.js。
的console.log(this.props.comments)返回我的根節點 '意見'

+1

你怎麼用'map'試試? – suvroc

+1

根據@suvroc - 評論*是一個數組。 –

+0

@suvroc,我編輯了我的問題 – yerassyl

回答

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
JSON對象

假設您已經有JSON.parse d字符串,您可以使用forEach進行迭代。 Map僅用於從您現有的值中返回一個新數組。

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

編輯:聽起來像this.props.comments是根對象。因此,上述

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); 

然後你就可以繼續和循環throught評論是這樣的:

data.comments.forEach(function(comment, index) { 
    console.log("Comments["+index+"]: "+comment); 
}); 

注:

一旦你的JSON被解析,你會得到一個包含一系列註釋的對象,這樣你就可以很容易地使用所有的Array.prototype使用它的方法包括forEachmap