Home > OS >  Javascript - Merge object while adding new fields to nested objects
Javascript - Merge object while adding new fields to nested objects

Time:06-20

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?

CodePudding user response:

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.

  1. Write your own deep merge function
  2. Use external library because, yes, others have done that already

In case you need the library, I suggest you try Lodash _.merge().

CodePudding user response:

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";
  • Related