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";
...
iwatakeshi
  • 697
  • 3
  • 17
  • 31
  • 1
    jQuery.extend, or for .. in loop through an object with your desired properties and set them on some object. For example, see http://stackoverflow.com/a/19776683/1008798 – Dalius Mar 01 '14 at 04:07

5 Answers5

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"
}
mikebridge
  • 4,209
  • 2
  • 40
  • 50
10

With ES6 Spread Operator:

someVar = {...someVar, color: "blue", font_size: "30px"}
Mohsen
  • 4,049
  • 1
  • 31
  • 31
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";
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Worked! @Dalius mentioned first something similar, but I will give it to you since you mentioned about "with". – iwatakeshi Mar 01 '14 at 04:21
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");
-3
var myvar ={};
myvar['color']='red';
myvar['width'] ='100px';
alert(myvar.color);

or alert(myvar['color']);

Maneesh Singh
  • 555
  • 2
  • 12
  • 1
    OP specifically requested a better approach than setting each property individually. – raychz Oct 30 '17 at 07:27
  • This is the dynamic assignment with respect to key, as like if key is any variable as `var col = 'color'; myvar[col] = 'red';` – Maneesh Singh Jan 05 '18 at 05:50