Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge with nested key in javascript spread operator?

I have the following objects like

obj1 = { key1: { a: 1}}

I want to merge the following object with the above

key1 = { b: 2}

I want to get the result as following by merging the key1 with the existing key in the first object.

{key1: {a: 1, b: 2}} 

How can I do this using spread operator in javascript? Thanks in advance.

like image 850
Hareesh Avatar asked Mar 05 '23 00:03

Hareesh


2 Answers

You can spread both existing and new object

Note: Using spread operator will only merge the enumerable properties.

const obj1 = { key1: { a: 1}}
const key1 = { b: 2};
const res = {...obj1,key1:{...obj1.key1,...key1}};
console.log(res)

If you want to modify the original object then only change obj.key1

const obj1 = { key1: { a: 1}}
const key1 = { b: 2};
obj1.key1 = {...obj1.key1,...key1}
console.log(obj1)
like image 78
Maheer Ali Avatar answered Mar 17 '23 23:03

Maheer Ali


Just use the spread operator like so:

let obj1 = {
  key1: {
    a: 1
  }
};

let key1 = {
  b: 2
};

obj1.key1 = { ...obj1.key1, ...key1 };
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: auto; }
like image 39
Jack Bashford Avatar answered Mar 17 '23 22:03

Jack Bashford