1

I'd like to be able to dynamically created a JSON object using a variable as the field name.

I've worked out how to set the field value from a variable using $() but it doesn't work for the field name.

    const body: string = JSON.stringify({
      '__metadata': {
        'type': listItemEntityTypeName
      },
      `${FIELD_NAME}`: `${FIELD_VALUE}`
    });

The error I get in VS Code is:

[ts] Cannot invoke and expression whose type lacks a call signature. Type '{ '__metadata': { 'type':string; }; }' has no compatible call signatures. [2349] [ts] Property assignment expected. [1136]

I'm using typescript and react. I'm fairly new JavaScript so forgive me if I'm missing something obvious.

Lymedo
  • 576
  • 9
  • 21
  • 4
    It should be `[FIELD_NAME]` not `\`${FIELD_NAME}\`` – zerkms Feb 03 '19 at 09:47
  • 1
    The term to look up here is "computed property names". – Ingo Bürk Feb 03 '19 at 09:47
  • 1
    Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – Jeto Feb 03 '19 at 09:49
  • Also, `${FIELD_VALUE}` (with the backticks around) can probably just be `FIELD_VALUE`, unless you want to convert any value into a string. – Jeto Feb 03 '19 at 09:51

2 Answers2

6

Anything that goes inside JSON.stringify should be a valid JSON Object

const body: string = JSON.stringify({
  '__metadata': {
    'type': listItemEntityTypeName
  },
  [FIELD_NAME]: `${FIELD_VALUE}`   // FIELD_VALUE should also be fine, if you dont want to convert it to string.
});

removing the string literal in the key can give you a valid JSON and hoepfully resolve the error

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
1

You can treat the object as an array.

var FIELD_NAME = 'hello'
var FIELD_VALUE = 'world'

var obj = {
    '__metadata': {
        'type': 'aaaa'
    },
}

obj[FIELD_NAME] = FIELD_VALUE

console.log('obj', obj)
vmf91
  • 1,897
  • 19
  • 27