Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS : Immutable.js : merge two Json objects

I'm using React, Redux & immutable. I tried to merge two Json objects, data and expected result is given below,

obj1 = 
{id: 1, first_name: "abc", surname: "def", children: ["kid1", "kid2"]}

obj2 = 
{first_name: "abc", surname: "def", email: "[email protected]", mobile: ""}

mergedObj = {id: 1, first_name: "abc", surname: "def", email: "[email protected]", Mobile: "",  children: ["kid1", "kid2"]}

If data is not available on obj1, it should be taken it from obj2.

I tried using immutable merge as outlined below,

import Immutable, {merge} from "immutable";
const mergedObj = merge(Immutable.fromJS(obj2), Immutable.fromJS(obj1));
console.log(mergedObj)

Result is same as obj2, essentially, merge is not happening,

{first_name: "abc", surname: "def", email: "[email protected]", mobile: ""}
like image 257
user3362908 Avatar asked Oct 14 '25 17:10

user3362908


1 Answers

You can do merge using javascript spread operator which is introduced in ES6 onwards.

var obj1 = {id: 1, first_name: "abc", surname: "def", children: ["kid1", "kid2"]}

var obj2 = {first_name: "abc", surname: "def", email: "[email protected]", mobile: ""}

var mergedObj = {...obj1,...obj2};
like image 59
Alwin Jose Avatar answered Oct 17 '25 06:10

Alwin Jose