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.
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.
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));
??
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));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With