31

I have two objects. And I want to merge the two objects but only the property value who is only present to the first object.

   obj1 : {
        "name": "",
        "age": ""
   }

  obj2 : {
        "name": "Leo",
        "age": "14",
        "company": "aero",
        "shift": "night"
  }

The output I want to be is:

  obj1 : {
        "name": "Leo",
        "age": "14"
   }

The company and shift is no need to merge because that 2 property is not present in obj1.

The code I've done so far is: Object.assign({}, obj1, obj2);

But it's not give me the right output. What it gives is:

 merge : {
        "name": "Leo",
        "age": "14",
        "company": "aero",
        "shift": "night"
  }

Could someone help me how to achieve the output like this:

  merge : {
        "name": "Leo",
        "age": "14",
  }

Many thanks!

4
  • 1
    Loop over the properties in the first object. Bring in the value from the second object if it is there. By the way, this has nothing to do in particular with either TypeScript or Angular.
    – user663031
    Nov 13, 2016 at 12:04
  • Yes. But I am trying to avoid looping if it's possible. It just makes the codes long.
    – Zero
    Nov 13, 2016 at 12:05
  • 1
    You can't avoid looping, one way or another.
    – user663031
    Nov 13, 2016 at 12:05
  • 1
    Object.assign also works for more than one level. All answers are solutions for one level. A solution for deep merge of only existing properties also matches the question‘s title, so we might better rephrase the title. Dec 17, 2021 at 20:12

6 Answers 6

33

Assuming you only want enumerable properties, this is easily done with Object.keys and in (or hasOwnProperty):

Object.keys(obj2).forEach(function(key) {
    if (key in obj1) { // or obj1.hasOwnProperty(key)
        obj1[key] = obj2[key];
    }
});

Example:

var obj1 = {
  "name": "",
  "age": ""
};

var obj2 = {
  "name": "Leo",
  "age": "14",
  "company": "aero",
  "shift": "night"
};

Object.keys(obj2).forEach(function(key) {
  if (key in obj1) { // or obj1.hasOwnProperty(key)
    obj1[key] = obj2[key];
  }
});
console.log(obj1);

Or in ES2015 syntax (since you mentioned Object.assign):

for (const key of Object.keys(obj2)) {
    if (key in obj1) { // or obj1.hasOwnProperty(key)
        obj1[key] = obj2[key];
    }
}

Or a more fluent approach, but revisits the keys that are in obj1 (not that it's likely to matter:

Object.keys(obj2).filter(key => key in obj1).forEach(key => {
    obj1[key] = obj2[key];
});

Since forEach ignores the return value of its callback, we could even go further in the concise-land:

Object.keys(obj2).filter(key => key in obj1).forEach(key => obj1[key] = obj2[key]);
8
  • Thanks for the answer. I will just test it and accept the answer later. Is there a way not use loop?
    – Zero
    Nov 13, 2016 at 12:08
  • 1
    @Zero: Object.assign uses a loop too, it's just not in your code. No, there's nothing built-in that won't involve some kind of looping. Nov 13, 2016 at 12:10
  • 3
    what about nested properties ?
    – addy
    Dec 6, 2018 at 7:03
  • 1
    @addy - The OP didn't need to handle nested properties. If you do, put the logic in a function and, when the property value is an object, recurse. Dec 6, 2018 at 7:50
  • 1
    @JoãoPimentelFerreira - See my comment to addy above. Dec 11, 2018 at 7:22
6

Here's a more functional approach using Array.prototype.reduce()

const obj1 = {
  "name": "",
  "age": ""
};

const obj2 = {
  "name": "Leo",
  "age": "14",
  "company": "aero",
  "shift": "night"
};

const newObject = Object.keys(obj1)
  .reduce(function(accumulator, key) {
    accumulator[key] = obj2[key]
    return accumulator
  }, {});

console.log(newObject);

Or some fun with ES6

const newObject = Object.keys(obj1)
  .reduce((a, key) => ({ ...a, [key]: obj2[key]}), {});
1
  • Although it is not clear how the question wished to address this case: your ES6 example will overwrite obj1 values with undefined if the key does not exist in obj2. Easily fixed with obj2[key] || obj1[key].
    – niborg
    Mar 5, 2020 at 23:25
3

Update 2020

const data = {a:1,b:2,b:3}
const form = {a:'',b:''}

for (const key in data) {
  if (key in form) {
    form[key] = data[key];
  }
}
console.log(form) // Output: {a:1,b:2}
1

Based off T.J. Crowder 's answer.

Here's a nested version of it:

const mergeFunction = (obj1, obj2) => {
  Object.keys(obj2).forEach(function (key) {
    if (key in obj1) {
      if (typeof obj1[key] === 'object') {
        mergeFunction(obj1[key], obj2[key]);
      } else {
        obj1[key] = obj2[key];
      }
    }
  });
};

Personally I don't like mutating the objects themselves so here's the version I use:

const mergeExisting = (obj1, obj2) => {
  const mutableObject1 = Object.assign({}, obj1);
  const mutableObject2 = Object.assign({}, obj2);

  mergeFunction(mutableObject1, mutableObject2);

  return mutableObject1;
};

const mergeFunction = (obj1, obj2) => {
  Object.keys(obj2).forEach(function (key) {
    if (key in obj1) {
      if (typeof obj1[key] === 'object') {
        mergeFunction(obj1[key], obj2[key]);
      } else {
        obj1[key] = obj2[key];
      }
    }
  });
};

Usage


const object1 = {
  name: 'test',
  addresses: [
    {
      country: '',
      postalCode: ''
    },
    {
      unitNumber: '',
      building: ''
    }
  ]
};

const object2 = {
  name: 'test',
  email: '[email protected]',
  description: 'urgh',
  addresses: [
    {
      country: 'SG',
      block: '6',
      street: 'Raffles Boulevard',
      unitNumber: '01-01',
      postalCode: '039594',
      building: 'Marina Square'
    },
    {
      country: 'SG',
      block: '6',
      street: 'Raffles Boulevard',
      unitNumber: '02-01',
      postalCode: '039594',
      building: 'Marina Square'
    }
  ]
};


mergeFunction(object1, object2);

// OR

const result = mergeExisting(object1, object2);


// Output
expect(result).toEqual({
  name: 'test',
  addresses: [
    { country: 'SG', postalCode: '039594' },
    { unitNumber: '02-01', building: 'Marina Square' }
  ]
});
0

Mutable

for (const [key, value] of Object.entries(obj2)) {
    if (obj1[key]) {
        obj1[key] = value;
    }
}

Immutable

const newObj = {};
for (const [key, value] of Object.entries(obj1)) {
    newObj[key] = obj2[key] || value;
}
-2

If you know the properties of the first object, you can use Typescript's Object deconstruction:

let obj2 = {
  "name": "Leo",
  "age": "14",
  "company": "aero",
  "shift": "night"
}
let { name, age } = obj2; // deconstruction
let merged = { name, age }; // shorthand object creation

If properties are unknown, you'll have to use loop, as suggested.

2
  • 1
    If you make that last line Object.assign(obj1, {name, age}) this seems like a possible approach given the caveat. It does require those temporary vars, but... Nov 13, 2016 at 12:31
  • 3
    This is not "TypeScript's" object deconstruction. It's just plain old ES6. Anyway, your solution won't work if one of the properties is missing from obj2.
    – user663031
    Nov 13, 2016 at 12:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.