Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain JS or Lodash - replace object values with values from other object

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?

like image 435
norr Avatar asked Mar 04 '23 19:03

norr


1 Answers

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)
like image 127
Akrion Avatar answered Apr 30 '23 01:04

Akrion