Merge two JSON object in javascript

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:

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:

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].

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]

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.

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:

c = {a: {title:'Semurjengkol in the night', author:'Amir Hamzah'},
b:{book: 'Puasa Siang Hari', page: 12}};

Leave a Reply

Your email address will not be published. Required fields are marked *