0

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}`: {}}

1 Answers1

5

Use square brackets!

const categoria = "Carros";

const obj = {
  categorias: {}
};

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

console.log(obj.categorias);
MikeM
  • 13,156
  • 2
  • 34
  • 47
  • Perfect! I didn't know about this feature. Thank you very much. – Otavio Fagundes Oct 07 '21 at 16:30
  • You're welcome. It's a [computed property name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names)". – MikeM Oct 07 '21 at 16:31