Deep merge two json object react

154 Views Asked by At

I have two json object in which one is nested. For example:

data1 : [{"name": "abc", "age": 26, "title": "xyz", "address": {"street":"yyy","city":"ttt","country":"kkk"}]
date2: [{"color": "blue", "sqad": "jkl", "priority": "rst", "division": "opq", "range": 456}]

I tried to merge them using spread operator and also object.assign but not getting the expected result.

I need it combined like below:

[{"name": "abc", "age": 26, "title": "xyz", "color": "blue", "sqad": "jkl", "priority": "rst", "division": "opq", "range": 456 }]
2

There are 2 best solutions below

0
kiranvj On

Try this. This uses spread operator

    let data1 = [{"name": "abc", "age": 26, "title": "xyz" }];

    let data2= [{"color": "blue", "sqad": "jkl", "priority": "rst", "division": "opq", "range": 456}];  

    let mergedArray3 = [{...data1[0], ...data2[0]}];

    console.log(mergedArray3)

    let data1 = [{"name": "abc", "age": 26, "title": "xyz" }];

    let data2= [{"color": "blue", "sqad": "jkl", "priority": "rst", "division": "opq", "range": 456}];  
    let mergedArray3 = [{...data1[0], ...data2[0]}];
    
    console.log(mergedArray3)

0
mstoJS On
 let data1 = [{"name": "abc", "age": 26, "title": "xyz" }];
 let data2= [{"color": "blue", "sqad": "jkl", "priority": "rst",
 "division": "opq", "range": 456}];  

 let newObj = Object.assign(data1[0], data2[0]);