merging javascript arrays for json

Posted by Nat on Stack Overflow See other posts from Stack Overflow or by Nat
Published on 2010-05-22T02:15:35Z Indexed on 2010/05/22 2:20 UTC
Read the original article Hit count: 253

Filed under:
|
|
|

I serially collect information from forms into arrays like so:

list = {"name" : "John", "email" : "[email protected]", "country" : "Canada", "color" : "blue"};  
identifier = "first_round";

list = {"name" : "Harry", "email" : "[email protected]", "country" : "Germany"};  
identifier = "second_round";

I want to combine them into something (I may have braces where I need brackets) like:

list_all = {  
"first_round" :  
 {"name" : "John", "email" : "[email protected]", "country" : "Canada", "color" : "blue"} ,  
"second_round" :  
{"name" : "Harry", "email" : "[email protected]", "country" : "Germany"}  
 };

so I can access them like:

alert(list_all.first_round.name) -> John

(Note: the name-values ("name", "email", "color") in the two list-arrays are not quite the same, the number of items in each list-array is limited but not known in advance; I need to serially add only one array to the previous structure each round and there may be any number of rounds, i.e. "third-round" : {...}, "fourth-round" : {...} and so on.)

Ultimately, I'd like it to be well-parsed for JSON.

I use the jquery library, if that helps.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about array