Christina
Christina

Reputation: 189

Deep merge two json object es6

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", "address": {"street":"yyy","city":"ttt","country":"kkk"}, "color": "blue", "sqad": "jkl", "priority": "rst", "division": "opq", "range": 456 }]

Upvotes: 1

Views: 1692

Answers (2)

Yosvel Quintero
Yosvel Quintero

Reputation: 19090

You can use a combination of recursion and the spread operator:

const deepMerge = (objs) =>
  objs.reduce((acc, obj) =>
    Object.keys(obj).reduce((innerAcc, key) => ({
      ...innerAcc,
      [key]:
        key in acc
          ? typeof acc[key] === 'object' && acc[key] !== null && typeof obj[key] === 'object' && obj[key] !== null
            ? deepMerge([acc[key], obj[key]])
            : obj[key]
          : obj[key]
    }), acc),
  {})

const data1 = { name: 'abc', age: 26, title: 'xyz', address: { street: 'yyy', city: 'ttt', country: 'kkk' } }
const data2 = { color: 'blue', squad: 'jkl', priority: 'rst', division: 'opq', range: 456 }

const result = deepMerge([data1, data2])

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Soumya Ranjan Swain
Soumya Ranjan Swain

Reputation: 187

You can use something like this:

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

var data3 = [Object.assign( {}, data1[0], data2[0] )];

Hope this answers your query

Upvotes: 1

Related Questions