2

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?

Raul
  • 2,673
  • 1
  • 15
  • 52

3 Answers3

3

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().

holydragon
  • 6,158
  • 6
  • 39
  • 62
2

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";
Yoz
  • 707
  • 6
  • 20
  • 1
    Have to note that this is not a language feature though. Depends on the runtime environment whether or not this function will be available. – Robby Cornelissen Jun 20 '22 at 09:38
1

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",
    }
}

}

Ekene Madunagu
  • 323
  • 1
  • 3
  • 7