简体   繁体   中英

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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM