Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading