Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign multiple values to a JavaScript object?

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";
...
like image 319
iwatakeshi Avatar asked Mar 01 '14 04:03

iwatakeshi


People also ask

How set multiple values in JavaScript?

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.

How do you assign multiple values?

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.

Can a variable hold multiple values in JavaScript?

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.

Can a Key have multiple values JavaScript?

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.


1 Answers

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"
}
like image 115
mikebridge Avatar answered Oct 23 '22 23:10

mikebridge