Create Dynamic Keys for JavaScript objects
When I'm building a JavaScript object dynamically I often want dynamic keys, or better said, keys that are dynamic at build-time of the object. It's actually simple, but I always forget the syntax, so if you're just looking for that it looks like this, assuming you have a javascript object already declared called obj:
obj['key' + someVal] = 'some value ' + someVal
Example Usage
I've found myself receiving an API response from a back-end and needing to build a JavaScript object based on that API response but needing validation on the response to make sure it is correctly shaped. You might do this with something like:const dynamicObject = {} // apiResponse would normally be done with something like const apiResponse = fetch(url) but statically setting for illustration purposes const apiResponse = { someKey1: 'someValue1', someKey2: 2, someKey3: 'someValue3', someKey4: 'someValue4', } const someValidationFunction = (value) => typeof value === 'string' Object.keys(apiResponse).forEach((key) => { if (someValidationFunction(apiResponse[key])) { dynamicObject[key] = apiResponse[key] } }); console.log(dynamicObject) // Expected output: // { // someKey1 = 'someValue1', // someKey3 = 'someValue3', // someKey4 = 'someValue4', // }To try it yourself check out this codepen. You'll need to click the "Console" button on the bottom left to see the result.
Anonymous comments not allowed. Please login or create an account to leave a comment.