Skip to content Skip to sidebar Skip to footer

Deep Merging Two Javascript Objects Lodash/vanilla

I am trying to merge two Objects with containing objects..which contain an array of object..you got the idea. But, my code just not producing the desired result, and I can't unders

Solution 1:

You could iterate the keys of the object and update only if the target has null values.

functionupdate(source, target) {
    Object.keys(source).forEach(function (k) {
        if (target[k] === null) {
            target[k] = source[k];
            return;
        }
        if (source[k] && typeof source[k] === 'object') {
            update(source[k], target[k]);
        }
    });
}

var source = { a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa", d: [{ a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa" }, { a: "bbbb", Id: 2, b: { a: "bbb", Id: 3 }, c: "aaa" }] },
    target = { a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null, d: [{ a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null }, { a: "aaa", Id: 2, b: { a: "aaa", Id: 3 }, c: null }] };

update(source, target);

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

Post a Comment for "Deep Merging Two Javascript Objects Lodash/vanilla"