I'm working with a JavaScript object that gives the default values for a library I am working with
const defaults = {
alpha: alpha_val,
beta: {
a: {
i: beta_a_i_val,
ii: beta_a_ii_val,
},
c: beta_c_val,
},
gamma: gamma_val,
};
So far, I've been overriding the defaults in the following way
const override = {
...defaults,
beta: {
...defaults.beta,
a: {
...defaults.beta.a,
i: beta_a_i_newval,
},
},
gamma: gamma_newval,
};
While this works, the true defaults object is quite large and so overrides of many values becomes tedious and ugly.
I'm wondering if there is a way to write a function to do this sort of "deep spread" automatically?
So, creating the override object above, for example, would look something like this:
const newvals = {
beta: {
a: {
i: beta_a_i_newval,
},
},
gamma: gamma_newval,
};
const overrides = someFunction(defaults, newVals)
It seems like this would be a common requirement, but I've been having trouble finding a way to actually do this. I'm very new to JavaScript, so any advice is greatly appreciated!
Yes, you can write a function that takes in the defaults object and the newvals object, and returns a new object that combines the two. One way to do this would be to use a recursive function, where you loop through the keys in the newvals object and perform a "deep spread" similar to what you did before.
Here is an example of how you could write the someFunction function:
This function works by creating a new object called result that is a shallow copy of the defaults object. It then loops through the keys in the newvals object and checks if the value is an object. If it is, it calls the someFunction function recursively to merge the two objects. If the value is not an object, it simply assigns the new value to the key in the result object.
You can then use the someFunction function like this: