我連續收集形式的信息到陣列像這樣:合併JavaScript數組的JSON
list = {"name" : "John", "email" : "[email protected]", "country" : "Canada", "color" : "blue"};
identifier = "first_round";
list = {"name" : "Harry", "email" : "[email protected]", "country" : "Germany"};
identifier = "second_round";
我想將它們組合成的東西(我可能有,我需要括號大括號),如:
list_all = {
"first_round" :
{"name" : "John", "email" : "[email protected]", "country" : "Canada", "color" : "blue"} ,
"second_round" :
{"name" : "Harry", "email" : "[email protected]", "country" : "Germany"}
};
這樣我就可以訪問他們喜歡的:
alert(list_all.first_round.name) -> John
(注:兩個列表中的名稱值(「名」,「電子郵件」,「顏色」) - 陣列並不完全相同,每個列表陣列中的項目數量有限,但事先不知道;我需要在每一輪中只向前一個結構添加一個數組,並且可能有任意數量的輪次,即「第三輪」:{...},「第四輪」:{...}等等)
最終,我希望它能夠很好地解析JSON。
我使用jQuery庫,如果有幫助。
在旁註,如果你列舉list_all的屬性,如'的(在list_all VAR鍵)',順序屬性不保證。即使首先定義了「first_round」,您也可能會在「first_round」之前獲得「second_round」。如果您希望保留訂單,請改用數組。見 - http://stackoverflow.com/questions/648139/is-the-order-of-fields-in-a-javascript-object-predicatble-when-looping-through-th – Anurag 2010-05-22 03:31:05
但是,什麼時候屬性的順序任何重要的對象? 如果訂單很重要,則Array是要使用的類型。 – 2010-05-22 12:33:04
@Sean - 當你想要用鍵直接訪問元素,但同時也想按順序迭代所有元素。認爲某人可能需要它並不荒謬--Ruby在1.9中改變了Hash的實現以保證訂單,因爲有人需要它。 – Anurag 2010-05-24 19:20:36