Home > Software engineering >  How to use the value of a variable as a property of an object?
How to use the value of a variable as a property of an object?

Time:10-08

In the example below, the object doesn't seem to understand which category is a variable and so it uses as a string:

var categoria = "Carros";
var obj       = {
    categorias: {}
};
obj.categorias = {...obj.categorias, categoria: {}}
console.log(obj.categorias)

I want the category property to be named "Cars" and not category. I tried it the way below, but it returns a template string error:

var categoria = "Carros";
var obj       = {
    categorias: {}
};
obj.categorias = {...obj.categorias, `${categoria}`: {}}

CodePudding user response:

Use square brackets!

const categoria = "Carros";

const obj = {
  categorias: {}
};

obj.categorias = { ...obj.categorias, [categoria]: {} };

console.log(obj.categorias);

  • Related