Say that I have an object with key/value pair as the following:
var someVar = {
color: "white",
font_size: "30px",
font_weight: "normal"
...some more variables and functions
};
Is there a way to do a multiple assignment to those keys instead of having to do something like this:
someVar.color = "blue";
someVar.font_size = "30px";
...
You can set multiple variables to the same value in JavaScript by using the equal sign (=) consecutively between the variable names and assigning a single value at the end when declaring the variables. var c = 10; var b = c; var a = b; You can also declare the variables first and assign the value later.
You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.
There is no way to assign multiple distinct values to a single variable. An alternative is to have variable be an Array , and you can check to see if enteredval is in the array. To modify arrays after you have instantiated them, take a look at push , pop , shift , and unshift for adding/removing values.
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
With ES2015 you can use Object.assign
:
const someVar = {
color: "white",
font_size: "30px",
font_weight: "normal"
};
const newVar = Object.assign({}, someVar, {
color: "blue",
font_size: "30px"});
console.log(newVar);
=>
{
color: "blue",
font_size: "30px",
font_weight: "normal"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With