0

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?

Muirik
  • 6,049
  • 7
  • 58
  • 116

2 Answers2

3

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.

mkemaltas
  • 154
  • 3
  • 1
    It works like a charm, better than my solution, so if you can use ES6 this is preferred. – Firewizz Nov 08 '21 at 14:49
  • While it indeed works, it is basically repeating what is said [here](https://stackoverflow.com/a/2274327). It is discouraged to answer questions that are already answered on Stack Overflow. See [Why are some questions marked as duplicate?](https://stackoverflow.com/help/duplicates) (Users above 15 reputation and below 3000 reputation [can flag](https://stackoverflow.com/help/privileges/flag-posts) questions as duplicate.) – Ivar Nov 08 '21 at 14:58
1

Something like this should do the trick.

const dynObj = {};
dynObj[fieldType] = value;  
const updatedItemsArr = [...this.state.targetItems, dynObj];
Firewizz
  • 773
  • 5
  • 17