2 ms·
Is this bit of code considered kosher javascript? {[path]: payload} I don't think I have seen this before... it looks like a short cut to get a dynamic key.
by jcampbell1 7y ago
Is this bit of code considered kosher javascript?
{[path]: payload}
I don't think I have seen this before... it looks like a short cut to get a dynamic key. I can't decide whether I like it or hate it. It is new to me, and it seems like typescript won't understand it. You will also have a bad time if path === 'constructor'.
- wrkronmiller 7y agoYes, it creates an object with key as the value of path and value the value of payload. If path=1, payload=2, this call would make the object {‘1’: 2 }
- jcampbell1 7y agoThat is what I thought, and if path = ['foo','bar'] and payload = 2, it makes {'foo,bar',2}. It is for sure making max use of dynamic programming. Typescript accepts it as {[path as any]: payload} which is pulling ejection lever on typescript. Glad I learned something new from this.
- PudgePacket 7y agoIt's just a nice quality of life improvement compared to const obj = {}; obj[foo] = 10;