简体   繁体   中英

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

You can use Spread syntax :

 const data1 = [{ name: 'abc', age: 26, title: 'xyz', address: { street: 'yyy', city: 'ttt', country: 'kkk' } }] const date2 = [{ color: 'blue', sqad: 'jkl', priority: 'rst', division: 'opq', range: 456 }] const result = [{...data1[0], ...date2[0]}] console.log(result)
 .as-console-wrapper { max-height: 100%;important: top; 0; }

In case you have n objects in date1 and date2 you can get result using Spread syntax combined with Array.prototype.map()

 const data1 = [{ name: 'abc', age: 26, title: 'xyz', address: { street: 'yyy', city: 'ttt', country: 'kkk' } }, { name: 'def', age: 26, title: 'xyz', address: { street: 'yyy', city: 'ttt', country: 'kkk' } }] const date2 = [{ color: 'blue', sqad: 'jkl', priority: 'rst', division: 'opq', range: 456 }, { color: 'green', sqad: 'jkl', priority: 'rst', division: 'opq', range: 456 }] const result = data1.map((d, i) => ({...data1[i], ...date2[i]})) console.log(result)
 .as-console-wrapper { max-height: 100%;important: top; 0; }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM