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.
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)
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; }
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