Why can I not set a key
in a newly created object like this:
const baseObject = {key: "a", val: "b"}
const modifiedObject = {baseObject.val: baseObject.key} // SyntaxError: Unexpected token '.'
But instead using brackets is ok:
const modifiedObject = {[baseObject.val]: baseObject.key} // OK
From my understanding [baseObject.val]
should create a new array from the baseObject.val
with only that item in it. Can you explain why this works? Is this the best practice approach on setting a key
from an object's nested property?
I tried finding information on MDN and other sources but could not find any. I assume my search phrases are wrong since there should be a pretty basic explanation. Feel free to mark as duplicate if you can link me to already provided answers.