Introduction
Suppose we have a task to create an object with dynamic key value pairs. We would start with writing some logic to achieve it. But if we are aware of a feature name computed property of ES6, our life is sorted :P
Let's start with this....
What is an object?
Let us consider a real life scenario.
A car is an object. A car has properties like weight,color, height, width, etc.
Objects are like variables which can contain many values.
Like:
var obj = {};
OR
var car = {type:"Fiat", model:"500", color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
OR
objectName["propertyName"]
Now, we can get to dynamic properties
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
Suppose we have a task of creating an object from an array. We will have to create key value pairs.
Consider an array like:
const personsList = ["Alan", "Smith", "Kelly", "Jason", "Nicole"];
Now to create an object out of this array with key value pairs, we can use computed property feature available in ES6 as below:
let personsObject = {}; //create an object
//Iterate over the personsList array
personsList.forEach((currentItem, index) => {
personsObject[index] = currentItem;
});
console.log(personsObject);
// > {0: "Alan", 1: "Smith", 2: "Kelly", 3: "Jason", 4: "Nicole"}
As you can see now we have an object with dynamic key-value pairs. You can give custom key name instead of index.
For example:
personsList.forEach((currentItem, index) => {
// personsObject[index] = currentItem;
personsObject["name"] = currentItem;
});
console.log(personsObject);
// > {name: "Alan", name: "Smith", name: "Kelly", name: "Jason", name: "Nicole"}
Hope this helps you in some way.
Cheers !!!
You are wrong in last example! Javascript objects cannot have same property names. In your last example the result will be {name: "Nicole"}