patternjavascriptMinor
Mapping object values from one object to another
Viewed 0 times
fromoneanothervaluesmappingobject
Problem
I have an object called
For example, if I use this method like so:
I would expect
I'm using jQuery's
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.Solution
jQuery has
http://api.jquery.com/jquery.extend/
Otherwise, if you don't want to use jQuery at all, you can make a for loop:
As a side, your if statement isn't doing anything because both cases assign the value to configOptions.
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; // trueAs a side, your if statement isn't doing anything because both cases assign the value to configOptions.
Code Snippets
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; // trueContext
StackExchange Code Review Q#63161, answer score: 3
Revisions (0)
No revisions yet.