Raul
Raul

Reputation: 3081

Javascript - Merge object while adding new fields to nested objects

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?

Upvotes: 2

Views: 498

Answers (3)

Ekene Madunagu
Ekene Madunagu

Reputation: 333

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

}

Upvotes: 1

holydragon
holydragon

Reputation: 6728

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

Upvotes: 3

Yoz
Yoz

Reputation: 980

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

Upvotes: 2

Related Questions