Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update javascript object with another object, but only existing keys

Tags:

javascript

Is there a function, either in Javascript or Lodash, in which I can "update" one object with values from another object, but without adding new keys?

var foo = { 'a': 0, 'b': 1 }
var bar = { 'b': 2, 'c': 3 }

Something like update(foo, bar), overwriting ("updating") any existing keys, but not adding non-existing keys:

{ 'a': 0, 'b': 2 }

There's almost certainly a similar question like this on StackOverflow, but I've not been able to find it.

like image 720
svenema Avatar asked Jul 12 '20 17:07

svenema


1 Answers

Following are some of the ways you could achieve the desired result.

Instead of modifying the original objects, following code snippets create a new object with all the keys of the target object.

Using Nullish Coalescing Operator (??)

Nullish coalescing operator returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. For more details on this operator, see Nullish coalescing operator (??)

var foo = { 'a': 0, 'b': 1 }
var bar = { 'b': 2, 'c': 3 }

function update(target, src) {
  const res = {};
  Object.keys(target)
        .forEach(k => res[k] = (src[k] ?? target[k]));
  return res;
}

console.log(update(foo, bar));

Using hasOwnPropery() method

?? operator will fail for properties with null or undefined values. As an alternative, you could use hasOwnProperty() method. For details on this method, see Object.prototype.hasOwnProperty()

var foo = { 'a': 0, 'b': 1 }
var bar = { 'b': 2, 'c': 3 }

function update(target, src) {
  const res = {};
  Object.keys(target)
        .forEach(k => res[k] = (src.hasOwnProperty(k) ? src[k] : target[k]));
  return res;
}

console.log(update(foo, bar));

Using 'in' operator

You could also use in operator to check for property existence in source object but keep in mind that in operator returns true if the specified property is in the specified object or its prototype chain. For details on in operator, see in operator

var foo = { 'a': 0, 'b': 1 }
var bar = { 'b': 2, 'c': 3 }

function update(target, src) {
  const res = {};
  Object.keys(target)
        .forEach(k => res[k] = (k in src ? src[k] : target[k]));
  return res;
}

console.log(update(foo, bar));
like image 72
Yousaf Avatar answered Nov 15 '22 04:11

Yousaf