Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!