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);
const merge = (target, obj) => Object.keys (obj).reduce ((merged, key) => ({...merged, [key]: [obj[key]].reduce(merge, target[key]) || obj[key]}), target) for a super unreadable one liner :PI 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>