Es6 calculation Properties

var obj = {
    [name]()=>{
        
    }
}
What problem is this new feature of

es6"s calculation properties designed to solve?

Apr.02,2021

I know that you can declare a variable and use

as a property for an object.
var name= 'nickName'
var obj = {
    [name]:''
}

how can an array in this format be converted to an object?

["38:21","33:12","11:22"]

want to convert it to an object with the following structure

{ 
    38:21
    33:12, 
    11:22 
}

answer, using the calculation property, by default, the variable cannot be directly used as the property name of the object.
add a [] symbol to it and it can be parsed to the corresponding value of the variable. In the following solution, kv [0] is a variable, and when you build the object, the outer brackets (that is, the calculated attribute) are correctly parsed to the corresponding value of this variable.

["38:21","33:12","11:22"].map(o=>{
   let kv = o.split(":");
   return {[kv[0]]:kv[1]}
})

this is more convenient when you need to define this property with a constant

constants.js
    export const TEST = 'TEST'

index.js
    import { TEST } from 'contants.js'
     var obj = {
        [TEST]:''
    }

is very flexible, for example, it can be proxied. Many mvvm frameworks, such as Vue, use the source code

.
Object.keys(app.data).forEach(prop=>{
    //
    app.data[prop] = Object.defineProperty(app.data, prop, {       
    })
})

otherwise how do you set variables for properties?

Menu