JavaScript-在将新字段添加到嵌套对象的同时合并对象
我有以下对象:
const config = {
name: "app",
android: {
name: "app-android",
googleMaps: {
location: "us",
}
}
}
我想创建一个新的对象dynamicConfig
,它复制config
对象,但将某些字段添加到android.googlemaps
:
const dynamicConfig = {
...config,
android: {
...config.android,
googleMaps: {
...config.android.googleMaps,
endPoint: "some-endpoint",
apiKey: "some-api-key",
}
}
}
还有其他更干净的方法来处理此问题吗?我必须多次传播吗?
I have the following object:
const config = {
name: "app",
android: {
name: "app-android",
googleMaps: {
location: "us",
}
}
}
and I want to create a new object dynamicConfig
, which copies the config
object but adding some fields to android.googleMaps
:
const dynamicConfig = {
...config,
android: {
...config.android,
googleMaps: {
...config.android.googleMaps,
endPoint: "some-endpoint",
apiKey: "some-api-key",
}
}
}
Is there any other cleaner way to handle this? Do I have to spread multiple times?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您要问的是如何做深层合并,我强烈建议您检查首先。
因此,不幸的是,您现在将看到有2个主要选项适合您。
如果您需要库,我建议您尝试 lodash _。merge()。
What you are asking is how to do Deep Merge, which I highly suggest you check this out first.
So, you will now see that there are, unfortunately, 2 main options for you.
In case you need the library, I suggest you try Lodash _.merge().
您可以尝试这样。 structuredclone()创建一个具有给定值的深克隆
You can try like this. structuredClone() creates a deep clone of a given value
我建议使用 lodash Merge ,这是最简单的深入合并方法。例如:
结果:
}
I suggest using Lodash Merge, it is the easiest way to deep merge. For example:
Result:
}