简体   繁体   中英

Add object and array for same properties

var obj = {x:{y: {a: 1, b:2}}, p: 11}

var arr = [{x: {y: {c: 3}}},{x: {y: {d: 4}}}]

it can be done by lodash merge(obj, ...arr) but I don't want to use lodash merge method

outputObj = {x:{y: {a: 1, b:2, c: 3, d: 4}}, p: 11}

You could take an iterative and recursive approach and check the type of the value and take either an array or object if a parent property is not given.

 function merge(target, ...source) { source.forEach(s => Object.entries(s).forEach(([k, v]) => { if (v && typeof v === 'object') { merge(target[k] = target[k] || (Array.isArray(v) ? [] : {}), v); } else { target[k] = v; } })); } var obj = { x: { y: { a: 1, b: 2 } }, p: 11 }, arr = [{ x: { y: { c: 3 } } }, { x: { y: { d: 4 } } }] merge(obj, ...arr) console.log(obj); 

I found you can do this in "one line" using recursive reduction

 const merge = (target, obj) => Object.keys (obj).reduce((merged, key) => ({ ...merged, [key]:[obj[key]].reduce(merge, target[key])||obj[key] }), target), merged = arr.reduce (merge,obj); console.log (merged); 
 <script> var obj = {x:{y: {a: 1, b:2}}, p: 11} var arr = [{x: {y: {c: 3}}},{x: {y: {d: 4}}}] </script> 

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