Dynamic property name in Javascript

Question:

I have the following code:

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

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

meuObjeto.Propriedade1

And the return would be: "valor" . In other words, it would be the same as:

var meuObjeto = {
    Propriedade1 : "valor"
}

Is it possible to do that?

Answer:

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

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

If you want to assign the name value it will be

meuObjeto[nomePropriedade] = meuObjeto.nome;

If what you want is to replace the nome property then that doesn't work, that is, rename doesn't work. You have to create a new property and delete the old one.

In this case of replacement you must do:

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

note:

In the new ECMAScript 6 version (ECMAScript 2015) it is already possible to define objects with dynamic parameters when creating the Object. This is called [computed prope

Example:

function foo() { return 1; }
var o = {
  [foo() + 1]: 'foo bar'
};
console.log(o); // dá: Object {2: "foo bar"}
Scroll to Top