JavaScript: Computed property names

In this tutorial we will check how use computed property names to create objects with property names that result from computing an expression.

Introduction

In this tutorial we will check how use computed property names to create objects with property names that result from computing an expression, as the name implies.

To use computed property names, we simply use square brackets and put an expression inside them, when creating the object, like illustrated below.

var obj = {[expression]: propertyValue}

The code

To get started, we will test computed property names using a variable. So, we will assign a string to a variable and then use it as a property name of an object.

const propertyName = "x";

const obj = {
    [propertyName]: 10
}

console.log(obj);

You can check below at figure 1 the result. As can be seen, no error occurs and the property is correctly computed. Our final object has a property called “x”, which was the value of the variable.

Result of using a variable as property.
Figure 1 – Result of using a variable as property.

Now, instead of using a variable, we will put a string concatenation directly inside the square brackets, to obtain the final property name.

const obj2 = {
    ["x"+"y"]: 10
}

console.log(obj2);

You can check the result below at figure 2.

Result of using a string concatenation as property.
Figure 2 – Result of using a string concatenation as property.

We will check another possibility, which is using the result of a function call as expression inside the square brackets, to obtain the property name.

function test(){
    return "y"
}

const obj3 = {
    [test()]: 10
}

console.log(obj3);

Figure 3 illustrates the result.

Result of using the output of a function as property.
Figure 3Result of using the output of a function as property.

As a final example, we will use the value of an object’s property as the name of another object’s property, as shown below.

const baseObj = {
    prop : "z"
}

const obj4 = {
    [baseObj.prop]: 10
}

console.log(obj4);

The result can be seen at figure 4.

Result of using the output of a function as property.
Figure 4Result of using an object’s property value as property of other object.

Leave a Reply

%d bloggers like this: