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

135
Views
Using Dynamic Value to add Object to Array with the Spread Operator

I have some code within a function that looks like this:

 const updatedItemsArr = [...this.state.targetItems, {relationship: value}];

What I want to do is pass in a dynamic value in place of relationship. However, whatever I try ends up causing an error or is incorrect syntax.

This will not work:

const fieldType = 'relationship';
const updatedItemsArr = [...this.state.targetItems, {fieldType: value}];

Nor will this:

  const updatedItemsArr = [...this.state.targetItems, {`${fieldType}`: value}];

How can I pass in a dynamic value here?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In ES6 what you can do is you can put the dynamic key inside brackets. So

const updatedItemsArr = [...this.state.targetItems, {[fieldType]: value}];

should work.

about 4 years ago · Juan Pablo Isaza Report

0

Something like this should do the trick.

const dynObj = {};
dynObj[fieldType] = value;  
const updatedItemsArr = [...this.state.targetItems, dynObj];
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!