I have two objects:
let first = {
a: 'John',
b: 22,
c: 'example'
}
let second = {
b: 55,
d: 'demo'
}
I want to replace only already existing items from second object to first one. Result should look like this (so only b item should be changed, and new d item ignored):
{
a: 'John',
b: 55, // changed
c: 'example'
}
Merge will not work because it will add also new item. I can use foreach but I believe that there should be shorted answer for this. I'm already using lodash in my project so I can use function from there, but I cannot find any for this purpose. Is there any?
With lodash you could do something like this with _.merge
, _.pick
and _.keys
:
let first = {
a: 'John',
b: 22,
c: 'example'
}, second = {
b: 55,
d: 'demo'
}
let result = _.merge(first, _.pick(second, _.keys(first)))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
With ES6 you can use Object.keys and then Array.forEach on a new object like this:
let first = {
a: 'John',
b: 22,
c: 'example'
}, second = {
b: 55,
d: 'demo'
}, result = new Object(null)
Object.keys(first).forEach(k => result[k] = second[k] || first[k])
console.log(result)
This assumes you do not want to mutate
any of the objects. IF you do not care:
let first = {
a: 'John',
b: 22,
c: 'example'
}, second = {
b: 55,
d: 'demo'
}
Object.keys(first).forEach(k => first[k] = second[k] || first[k])
console.log(first)
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