1

My goal

My goal is merge the object including object in object. Example I have two objects A and B

Object A = {
   money: 100,
   'a':{money:20,happy:99}
   };
Object B = {
   happy: 100
   'a':{lucky:-5}
   };

I run merge code:

console.log(Object.assign({},A,B));

The result

had a little bit problem about properties of object in object you will see I lost some data until properties of object is fine

{
   money:100,
   happy:100,
   'a':{lucky:-5}
}

Expected

The result should be merge all including properties of object in object

{
   money:100,
   happy:100,
   'a':{money:20,happy:99,lucky:-5}
}

I tried to search about my question but I only found about merge object (not object in object) if this question is duplicated I apologise.

Found Solution for node (npm)

const mergeObj = require("object-merge-advanced");
mergeObj(A,B)

source: https://stackoverflow.com/a/51148924/11911474

Chat Dp
  • 555
  • 5
  • 15

1 Answers1

1

You need to iterate an merge single properties because Object.assign assigns only the first level with the new values.

function merge(a, b) {
    return Object.entries(b).reduce((r, [k, v]) => {
        if (v && typeof v === 'object') {
            merge(r[k] = r[k] || {}, v);
        } else {
            r[k] = v;
        }
        return r;
    }, a);    
};

var a = { money: 100, a: { money: 20, happy: 99 } },
    b = { happy: 100, a: { lucky: -5 } },
    merged = [a, b].reduce(merge, {});

console.log(merged);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392