简体   繁体   中英

merging javascript arrays for json

I serially collect information from forms into arrays like so:

list = {"name" : "John", "email" : "name@domain.com", "country" : "Canada", "color" : "blue"};  
identifier = "first_round";

list = {"name" : "Harry", "email" : "othername@domain.com", "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" : "name@domain.com", "country" : "Canada", "color" : "blue"} ,  
"second_round" :  
{"name" : "Harry", "email" : "othername@domain.com", "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, ie "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.

Create list_all as a new object as follows:

var list_all = {};
list_all[identifier_1] = list_1;
list_all[identifier_2] = list_2;
// ...

JSON uses object literal notation. The form:

var person = {
 "name": "Douglas Adams"
 "age": 42
};

Is exactly the same (for all intents and purposes) as:

var person = new Object();
person.name = "Douglas Adams";
person.age = 42;

Does that help you?

You can also use

person["age"]

this is the same as

person.age

and to iterate through named properties:

//prints the person.propertyName for all propertyName in person
for (var propertyName in person) {
 alert(person[propertyName]);
}

You can transmit data as a string, using it to interact with the server and converting it into an object, using jQuery. Ex:

var jsonString = "{'name': 'Douglas Adams', 'age': 42}";
jQuery.parseJson(jsonString); //returns this as an object

Search for JSON in the jQuery API docs: http://api.jquery.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM