I have an object called defaultOptions
and a function that accepts as an argument an object called newValues
meant to override the values in defaultOptions
with its own. The values that are not specified in newValues
should remain default.
var configOptions = {
isActive: false,
name: "",
description: "",
category: "",
group: "default"
}
publishOptions: function(newValues){
$.each(newValues, function(key, value){
if(configOptions.hasOwnProperty(key)){
configOptions[key] = value;
}
else{
configOptions[key] = value;
}
});
console.log(configOptions);
}
For example, if I use this method like so:
var myOptions = {
name: "option one",
category: "the best"
}
publishOptions(myOptions)
I would expect configOptions
to look like this:
configOptions = {
isActive: false,
name: "option one",
description: "",
category: "the best",
group: "default"
}
I'm using jQuery's each
method to map the values from newValues
to configOptions
, but I suspect there is a much more succinct and elegant way to do this. I would appreciate any suggestions.
-
\$\begingroup\$ You can also use ES6 spread syntax like: configOptions = {...configOptions, ...myOptions} \$\endgroup\$Pavan– Pavan2019年01月31日 09:37:04 +00:00Commented Jan 31, 2019 at 9:37
-
\$\begingroup\$ This may be true, but what's missing is why you would do this. Is it more efficient? Easier to read? Does it handle edge cases better? Is it more reliable? What is it about the original code that makes you suggest this alternative? \$\endgroup\$mdfst13– mdfst132019年01月31日 11:31:46 +00:00Commented Jan 31, 2019 at 11:31
2 Answers 2
jQuery has extend
, which seems to be what you are looking for:
http://api.jquery.com/jquery.extend/
Otherwise, if you don't want to use jQuery at all, you can make a for loop:
var first = { value: 1, string: "two" };
var second = { value: 2 };
for ( var i in second )
if ( first.hasOwnProperty( i ) )
first[i] = second[i];
first.value == 2; // true
As a side, your if statement isn't doing anything because both cases assign the value to configOptions.
You can use Lodash's merge function:
var defaultConfigOptions = {
isActive: false,
name: "",
description: "",
category: "",
group: "default"
}
var myOptions = {
name: "option one",
category: "the best"
}
var configOptions = _.merge({}, defaultConfigOptions, myOptions)
console.log(configOptions === defaultConfigOptions)
console.log("configOptions: ", configOptions)
console.log("defaultConfigOptions: ", defaultConfigOptions)
And this is what you will get:
See in jsbin: https://jsbin.com/jayihus/edit?js,console,output