Dynamic property name in Javascript

Asked

Viewed 1,611 times

11

I have the following code:

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

I would like the property name of meuObjeto received the variable value nomePropriedade.
Thus, when trying 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"
}


It is possible to do this?

3 answers

12


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

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

If you want to assign the name value will be

meuObjeto[nomePropriedade] = meuObjeto.nome;

If what you want is replace the property nome so that doesn’t work, which means Name doesn’t work. You have to create a new property and delete the previous one.

In this case of substitution you must 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 at the moment of creation of the Object. 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"}

4

If you only want to create and access variable properties, that is, create and access properties of an object dynamically, just use the brackets:

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

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

console.log( myObj[a], myObj.foo );

4

As a complement to the previous answers, it is also possible to dynamically verify whether the property has been defined, as follows

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

if (meuObjeto.hasOwnProperty(nomePropriedade)) {
    // Sim, possui a propriedade
}
  • 3

    Wallace, I’d just like to do a wake-up call, hasOwnProperty will return false if the property exists in the prototype and not in the object, in this case a typeof meuObjeto[nomePropriedade] !== 'undefined' It would work, certain that I doubt that the AP will need to use Constructors and Prototypes. You can see what I’m pointing at in this fiddle: https://jsfiddle.net/6nxmvsLx/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.