Merging javascript arrays for json

I sequentially collect information from forms into such arrays:

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 can have brackets where I need brackets), for example:

 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, for example:

 alert(list_all.first_round.name) -> John 

(Note: the name values ​​("name", "email address", "color") in the two list arrays are not exactly the same, the number of elements in each array list is limited, but it is not known in advance, I need to add only one array in sequence the previous structure each round, and there can be any number of rounds, that is, the "third round": {...}, the "fourth round": {...} and so on.)

Ultimately, I would like it to be well versed in JSON.

I am using jquery library if this helps.

+4
source share
2 answers

Create list_all as a new object as follows:

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

JSON uses object notation. The form:

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

The same (for all purposes and purposes):

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

Does this help you?

You can also use

 person["age"] 

it's the same as

 person.age 

and repeat the named properties:

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

You can transfer data as a string, using it to interact with the server and convert it to an object using jQuery. Example:

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

JSON search in jQuery API docs: http://api.jquery.com/

0
source

Source: https://habr.com/ru/post/1310580/


All Articles