merging javascript arrays for json
- by Nat
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.