[英]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'. 我有一个具有名为'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.
我可以使用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. Javascript解释器不能引用对象中的属性,即未创建,而不满足相应的右括号
}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.