Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
How can I create a dynamic object in a literal?

I have an object which includes several fields, most values are strings (constants) but I also want to use a variable (populated using some state)

const {order} = this.state;

myObject={{
    fieldA: 2,
    fieldB: ${order.value}
}}

I tried different variation of the above (with/without single quotes, etc.) but I am never able to set the value I need.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You are adding 2 brackets for an object which is not valid and no need of template literal.

const { order } = this.state;

const myObject = {
  fieldA: 2,
  fieldB: order.value,
};
about 4 years ago · Juan Pablo Isaza Relatório

0

If this.state looks like this:

this.state = {order: ""}

Declaring

const {order} = this.state

would just create a constant called order that is holding the value of this.state.order at the time order was declared. It will not be updated when this.state.order is updated.

If you want to set myObject.fieldB to hold a reference to the value of this.state.order, that is, the state value of order, do this:

const myObject = {
  fieldA: 2,
  fieldB: this.state.order,
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You have used two braces ('{}') which are not needed. The code should be like below

const myobject = {fieldA: 2, fieldB: order.value};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda