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.
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.
Share Improve this question edited May 10, 2019 at 11:15 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked May 10, 2019 at 11:12 HareeshHareesh 1,5874 gold badges21 silver badges48 bronze badges5 Answers
Reset to default 8You 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; }
You could splead it into the wanted property.
var obj1 = { key1: { a: 1 } },
key1 = { b: 2 };
obj1.key1 = { ...obj1.key1, ...key1 };
console.log(obj1);
Try this:
let obj1 = { key1: { a: 1}}
let b = { b: 2}
let a = obj1.key1; //{a:1}
// merge using spread operator
let key1 = {...a, ...b}; //{a:1, b:2}
obj1.key1 = key1; //{"a":1,"b":2"}
console.log(obj1) //{ "key1":{"a":1,"b":2"}}
You should use Object.assign
var obj1 = { key1: { a: 1}};
var key1 = { b: 2};
Object.assign(obj1.key1, key1);
console.log(obj1)