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?
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() .
You can try like this. structuredClone() creates a deep clone of a given value
const dynamicConfig = structuredClone(config);
dynamicConfig.android.googleMaps.endPoint = "some-endpoint";
dynamicConfig.android.googleMaps.apiKey= "some-api-key";
I suggest using Lodash Merge , it is the easiest way to deep merge. For example:
var merge = require('lodash.merge');
const config = {
name: "app",
android: {
name: "app-android",
googleMaps: {
location: "us",
}
}
}
const additionalConfig = {
android: {
googleMaps: {
endPoint: "some-endpoint",
apiKey: "some-api-key",
}
}
}
output = merge(config, additionalConfig);
console.log(output);
Result:
{
name: "app",
android: {
name: "app-android",
googleMaps: {
apiKey: "some-api-key",
endPoint: "some-endpoint",
location: "us",
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.