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

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer as always! - Check out 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 :P
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.