Practical guides, tutorials, and insights from years of building web and desktop applications. Check out code examples you can actually use!
Use variable value for object prop
How do you set a variable as the prop of an object? Consider the below code - const earth = { name: "earth" }; If we have a dynamic prop for earth, we can do - let lifeExists = "life"; const earth = { name: "earth" }; earth[lifeExists] = true; console.log(earth); // { name: 'earth', life: true } To define a new, dynamic prop - First we define the variable - lifeExists We then use that variable value as a prop and set the prop value earth[lifeExists] = true. Note that we cannot use earth.lifeExists = ... since we are not interested in lifeExists as a string literal, but only in its value (life) So, why use a dynamic prop? Because props may be set within our code or from the data retrieved from database. Javascript by itself will not be aware of all possible props for our object. ...