简体   繁体   中英

How to reference a sibling property for use in property name declaration? [object literal, Javascript, es6]

I have an object that has a property named 'type'. This type is the name of another property in the object. Can I achieve my desired output without breaking the declaration up into multiple parts by using Object Literal Syntax. Here is what I have, help is appreciated.

 // desired output // { // name: 'Tom Ford', // type: 'random-type', // 'random-type': { // title: 'Blah', // amount: 2000 // } // } var thisRefTest = { name: 'Tom Ford', type: getRandomType(), [this.type]: { title: 'Blah', amount: 2000 } } console.log('thisRefTest', thisRefTest) // output: // { // "name": "Tom Ford", // "type": "random-type", // "undefined": { // "title": "Blah", // "amount": 2000 // } // } var funcRefTest = { name: 'Tom Ford', type: getRandomType(), [function () { return this.type; }()]: { title: 'Blah', amount: 2000 } } console.log('funcRefTest', funcRefTest) // output: // { // "name": "Tom Ford", // "type": "random-type", // "undefined": { // "title": "Blah", // "amount": 2000 // } // } function getRandomType(){ return 'random-type'; } 

Only if you will define a variable with a value first

var type = getRandomType();
var thisRefTest = {
   name: 'Tom Ford',
   type: type,
   [type]: {
     title: 'Blah',
     amount: 2000
   }
};

The thing is that there is no object at the moment of instantiation. Javascript interpreter can't refer to a property in the object, that is not created, while corresponding closing bracket } is not met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM