[英]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
与第一个对象中的现有键合并来获得结果如下。
{key1: {a: 1, b: 2}}
How can I do this using spread operator in javascript? 如何在javascript中使用spread运算符执行此操作? Thanks in advance.
提前致谢。
You can spread both existing and new object 您可以传播现有对象和新对象
Note: Using spread operator will only merge the enumerable properties. 注意:使用spread运算符只会合并可枚举的属性。
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
如果要修改原始对象,则只更改
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: 只需像这样使用spread运算符:
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);
You should use Object.assign
你应该使用
Object.assign
var obj1 = { key1: { a: 1}}; var key1 = { b: 2}; Object.assign(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"}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.