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.

4
  • 4
    It should be [FIELD_NAME] not `${FIELD_NAME}` Commented Feb 3, 2019 at 9:47
  • 1
    The term to look up here is "computed property names". Commented Feb 3, 2019 at 9:47
  • 1
    Possible duplicate of How to use a variable for a key in a JavaScript object literal? Commented Feb 3, 2019 at 9:49
  • Also, ${FIELD_VALUE} (with the backticks around) can probably just be FIELD_VALUE, unless you want to convert any value into a string. Commented Feb 3, 2019 at 9:51

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

FIELD_NAME will just be FIELD_NAME as a key here. He has a variable of the same name.
Good catch @Jeto
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)

Comments

1

You can write your attribute name variable between square brackets, like this:

    const FIELD_NAME = 'Title';
    const FIELD_VALUE = 'New Title';
    const listItemEntityTypeName = 'Data.ListNameListItem';
    const body = JSON.stringify({
        __metadata: {
            type: listItemEntityTypeName,
        },
        [FIELD_NAME]: FIELD_VALUE,
    });
    
    console.log(body);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.