-2

There are 2 objects 1)

var obj1 = {
id: 1,
firstName: 'someFirst',
lastName: 'someLast',
status: 'active',
}

2)

var obj2 = {
firstName: 'test',
status: 'disable',
} 

how can I change the key value of the first object based on the key values of the second object? Expected result is:

obj1 = {
id: 1,
firstName: 'test',
lastName: 'someLast',
status: 'disable',
}

Many thanks!

3 Answers3

2
 Object.assign(/*to*/ obj1, /*of*/ obj2);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Object.assign(obj1, obj2) will merge the two objects together, where obj1 is the base object, and obj2 will replace any identical properties on the base object with its values.

In your example, this would return

{
  id: 1,
  firstName: 'text',
  lastName: 'someLast',
  status: 'disable',
}
Nathan Gingrich
  • 171
  • 1
  • 6
-1

You can do newObject = Object.assign({}, obj1, obj2).

Or use the object spread operator like: newObject = {...obj1, ...obj2}.

Do not mutate the original object.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317