Search code examples
javascriptreactjsstring-interpolation

String Interpolation in an Object


I've got the following code:

const [answerObject, setAnswerObject] = useState({})

const answerItem = {"question_" + survey.id, selectedAnswer}
setAnswerObject(answerObject + answerItem)

And I'm trying to get this result:

answers = {
    question_1: 'text from answer 1',
    question_2: 'text from answer 2',
    question_3: 'text from answer 3',
}  

However I'm having trouble interpolating it. I've tried a bunch of different methods with no luck. Any help or suggestions to format it properly would be great.


Solution

  • You can use an interpolated string for an object key by using square brackets.

    { 
      [`question_${survey.id}`]: selectedAnswer 
    }