JS Computed property names in Objects
Hi, there is a way to allow any property names and variables in object properties names.
Computed properties in an object is called when we insert brackets [ ] inside the object to declare property names, see this next example:
const propertyName = 'firstName';
let myObject = {
[propertyName] : 'Cristina', // This is a computed property and the name of this property will be the value of the const
lastName: 'Rojas'
}
console.log('myObject --->', myObject)
Result:
Also we can concatenate more things (variables, strings) inside the [ ] if we need it:
const propertyName = "first";
let myObject = {
[propertyName + "Name" + "User"]: "Cristina", // This is a computed property and the name of this property will be the value of the const and also the concatenation
lastName: "Rojas",
};
console.log("myObject --->", myObject);
Result:
Ok, this way of write property names can be implemented in objects that are more complex, like for example: if we need to create property names depending of some given name.
function makeUserObject(propertyName, propertyValue) {
let userObject = {};
userObject[propertyName] = propertyValue;
return userObject;
}
makeUserObject("firstName", "Cristina");
Result:
Also we can use the object literal notation for the same example and is more shorted:
function makeUserObject(propertyName, propertyValue) {
return {
[propertyName]: propertyValue,
};
}
makeUserObject("firstName", "Cristina");
Note: for this way you are going to use “:” instead of “=” to assign the values.
Result:
Nice, in ES6 we can add the properties with the computed name while creating the objects:
let myObject = {
["first" + "Name" + "User"] : "Cristina"
}
console.log(' value of the computed property --->', myObject["first" + "Name" + "User"])
Result:
By Cristina Rojas.