1

So I want to create a dynamic key in a js object. I know I can create it like this but id doesn't fullfil my requirements

return {
  [dynamicKey]: value
}

But the problem is I want something like this

return {
  [dynamicKey]_id: value
}

but it doesn't let me, I tried concatenating but it didn't work.

return {
  [dynamicKey] + '_id': value
}

I've also searched online for a solution but couldn't find any.

2
  • 4
    [dinamicKey + '_id']: value - the whole expression must be inside the square brackets. Commented Aug 2, 2021 at 20:09
  • Solved my problems, thx! Commented Aug 2, 2021 at 20:09

2 Answers 2

4

you need to put your _id string inside of the square brackets or as part of the dinamicKey var.

return {
  [dinamicKey + '_id']: value
}
dinamicKey += '_id';
return {
  [dinamicKey]: value
}
Sign up to request clarification or add additional context in comments.

Comments

0

Any expression in the square braces will be executed just like a normal expression. So how about this:

return {
    [dinamicKey + '_id']: value
}

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.