[英]How to use array destructuring and assign to an object property in JavaScript ES6
[英]How to reference a sibling property for use in property name declaration? [object literal, Javascript, es6]
我有一个具有名为'type'的属性的对象。 此类型是对象中另一个属性的名称。 我可以使用Object Literal Syntax在不将声明分成多个部分的情况下实现所需的输出。 这是我所拥有的,感谢帮助。
// 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'; }
仅当您首先定义具有值的变量时
var type = getRandomType();
var thisRefTest = {
name: 'Tom Ford',
type: type,
[type]: {
title: 'Blah',
amount: 2000
}
};
问题在于实例化时没有对象。 Javascript解释器不能引用对象中的属性,即未创建,而不满足相应的右括号}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.