Dynamic Javascript property name

10

I have the following code:

var nomePropriedade = "Propriedade1";
var meuObjeto = {
    "nome" : "valor"
}

I would like the property name of meuObjeto to receive the value of the nomePropriedade variable. Home So when I try to access the properties of meuObjeto I would have to do:

meuObjeto.Propriedade1

And the return would be: "valor" . That is, it would be the same as:

var meuObjeto = {
    Propriedade1 : "valor"
}


Is it possible to do this?

    
asked by anonymous 26.08.2015 / 16:27

3 answers

11

To create a property with a dynamic name as suggested you can use brackets like this:

var nomePropriedade = "Propriedade1";
var meuObjeto = {
    "nome" : "valor"
}
meuObjeto[nomePropriedade] = 'foo';

If you want to assign the name value,

meuObjeto[nomePropriedade] = meuObjeto.nome;

If you want to replace with the nome property then that does not work, ie rename does not. You need to create new property and delete it.

In this case of substitution you should do:

meuObjeto[nomePropriedade] = meuObjeto.nome;
delete meuObjeto.nome;

Note:

In the new version ECMAScript 6 (ECMAScript 2015) it is already possible to define objects with dynamic parameters when the object is created. It's called this [computed prope

Example:

function foo() { return 1; }
var o = {
  [foo() + 1]: 'foo bar'
};
console.log(o); // dá: Object {2: "foo bar"}
    
26.08.2015 / 16:37
3

If you just want to create and access variable properties, ie create and access properties of an object dynamically, simply use the brackets:

var a = 'foo'; 
var b = 'bar';

var myObj = new Object;
myObj[a] = b;

console.log( myObj[a], myObj.foo );
    
26.08.2015 / 16:43
3

As a complement to the previous answers, you can also dynamically check if the property has been defined, as follows

var nomePropriedade = "Propriedade1";
var meuObjeto = {
    "nome" : "valor"
}

if (meuObjeto.hasOwnProperty(nomePropriedade)) {
    // Sim, possui a propriedade
}
    
26.08.2015 / 17:13