0

i want a help here since i cannot find a proper solution: I have two objects:

obj1 = {
    name: '112',
    surname: { test: '123', other: '124' },
    age: 151,
    height: '183',
    weight: 80
  };

and

obj2 = {
    name: '114',
    surname: { test: '124' },
    age: 151,
    height: 184,
    weight: 81
  };

The new object must have this output:

new = {
        name: '114',
        surname: { test: '124', other: '124' },
        age: 151,
        height: 184,
        weight: 81
      };

You can see that in the surname propert the other property is kept: I've tried something like this but it's not working and there must be a simpler solution:

const newObje = Object.keys(obj2).reduce(newObj, key) => {
    if (typeof (obj2[key]) === 'string' || obj2[key] === 'number') {
      newObj[key] = obj2[key];
    }
    if (typeof (obj2[key]) === 'object' || obj2[key] === 'array') {

    }
  }
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
RamAlx
  • 6,976
  • 23
  • 58
  • 106

2 Answers2

1

You can use lodash .merge

_.merge(obj1 , obj2)

It will deep merge both objects as you can see in the docs

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

    let obj1 = {
        name: '112',
        surname: { test: '123', other: '124' },
        age: 151,
        height: '183',
        weight: 80
      };
      
    let obj2 = {
        name: '114',
        surname: { test: '124' },
        age: 151,
        height: 184,
        weight: 81
      };
      
let newObj = _.merge(obj1, obj2)

console.log(newObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
1

You could use a merging function and overwrite values with the last value.

function merge(...objects) {
    function m(t, s) {
        Object.entries(s).forEach(([k, v]) => {
            t[k] = v && typeof v === 'object' ? m(t[k] || {}, v) : v;
        });
        return t;
    }

    return objects.reduce(m, {});
}

var obj1 = { name: '112', surname: { test: '123', other: '124' }, age: 151, height: '183', weight: 80 },
    obj2 = { name: '114', surname: { test: '124' }, age: 151, height: 184, weight: 81 },
    result = merge(obj1, obj2);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392