Pergunta

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";
...
Foi útil?

Solução 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";
}

Outras dicas

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"
}

With ES6 Spread Operator:

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

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");
var myvar ={};
myvar['color']='red';
myvar['width'] ='100px';
alert(myvar.color);

or alert(myvar['color']);

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top