11

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";
...
1
  • 1
    jQuery.extend, or for .. in loop through an object with your desired properties and set them on some object. For example, see stackoverflow.com/a/19776683/1008798 Commented Mar 1, 2014 at 4:07

5 Answers 5

13

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"
}
Sign up to request clarification or add additional context in comments.

Comments

11

With ES6 Spread Operator:

someVar = {...someVar, color: "blue", font_size: "30px"}

Comments

3

You could loop through another object:

var thingsToAdd = {
    color: "blue",
    font_size: "30px"
};
for (var x in thingsToAdd) someVar[x] = thingsToAdd[x];

Or, you could use with (WARNING: this is ALMOST CERTAINLY a bad idea! See the link. I am only posting this for educational purposes; you should almost never use with in production code!):

with (someVar) {
    color = "blue";
    font_size = "30px";
}

1 Comment

Worked! @Dalius mentioned first something similar, but I will give it to you since you mentioned about "with".
0

I would use Object Constructors. Would look something like this:

function someVar (color,fontSize, fontWeight){
    this.color = color,
    this.fontSize = fontSize,
    this.fontWeight = fontWeight
};
var var1 = new someVar("red","12px","45px");

Comments

-3
var myvar ={};
myvar['color']='red';
myvar['width'] ='100px';
alert(myvar.color);

or alert(myvar['color']);

2 Comments

OP specifically requested a better approach than setting each property individually.
This is the dynamic assignment with respect to key, as like if key is any variable as var col = 'color'; myvar[col] = 'red';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.