JSON or JavaScript Object Notation, is a text-based data interchange format. JSON consists of key value pair with comma separated or an array or mixed both of them. Here an example of JSON:
1 | var a = {title: 'Semurjengkol in the night' , author: 'Amir Hamzah' }; |
Variable [cci]a[/cci] is JSON object which has two keys, [cci]title[/cci] and [cci]author[/cci]. Consider you have another JSON object:
1 | var b = {book: 'Puasa Siang Hari' , page: 12}; |
Our goal is to merge [cci]a[/cci] and [cci]b[/cci] to build new JSON object. There are two methods to merge two JSON Object.
Merge all of keys
Using this method, we combine all of keys from both [cci]a[/cci] and [cci]b[/cci] to build new JSON object which have keys from [cci]a[/cci] and [cci]b[/cci].
1 2 3 4 | var a = {title: 'Semurjengkol in the night' , author: 'Amir Hamzah' }; var b = {book: 'Puasa Siang Hari' , page: 12}; var c = a.merge(b); console.log(c); |
Method [cci]a.merge(b)[/cci] will return new JSON object which have all of keys from [cci]a[/cci] and [cci]b[/cci]. Here is the content of [cci]c[/cci]
1 | c = {title: 'Semurjengkol in the night' , author: 'Amir Hamzah' , book: 'Puasa Siang Hari' , page: 12}; |
Merge to one root
Another method to merge two JSON object is attach them into one root.
1 2 3 4 5 6 | var a = {title: 'Semurjengkol in the night' , author: 'Amir Hamzah' }; var b = {book: 'Puasa Siang Hari' , page: 12}; var c = {}; c[ 'a' ] = a; c[ 'b' ] = b; console.log(c); |
By using this method, the new JSON object [cci]c[/cci] will be like this:
1 2 | c = {a: {title: 'Semurjengkol in the night' , author: 'Amir Hamzah' }, b:{book: 'Puasa Siang Hari' , page: 12}}; |