简体   繁体   English

使用点符号作为键不可能从数组的对象创建修改后的数组

[英]Creating modified array from array's objects not possible with dot-notation as key

Why can I not set a key in a newly created object like this:为什么我不能像这样在新创建的 object 中设置key

const baseObject = {key: "a", val: "b"}
const modifiedObject = {baseObject.val: baseObject.key} // SyntaxError: Unexpected token '.'

But instead using brackets is ok:但是使用括号是可以的:

const modifiedObject = {[baseObject.val]: baseObject.key} // OK

From my understanding [baseObject.val] should create a new array from the baseObject.val with only that item in it.根据我的理解, [baseObject.val]应该从baseObject.val创建一个新数组,其中只有该项目。 Can you explain why this works?你能解释一下为什么会这样吗? Is this the best practice approach on setting a key from an object's nested property?这是从对象的嵌套属性设置key的最佳实践方法吗?

I tried finding information on MDN and other sources but could not find any.我尝试在 MDN 和其他来源上查找信息,但找不到任何信息。 I assume my search phrases are wrong since there should be a pretty basic explanation.我假设我的搜索短语是错误的,因为应该有一个非常基本的解释。 Feel free to mark as duplicate if you can link me to already provided answers.如果您可以将我链接到已提供的答案,请随时标记为重复。

What you have with [baseObject.val] is not an array, but a "computed property name" , a special syntax for object literals. [baseObject.val]所拥有的不是数组,而是“计算属性名称” ,这是 object 文字的特殊语法。

What it does is, when inside an object literal where a key should be, it evaluates the expression inside the brackets and then defines a property on the object being constructed with that expression.它所做的是,当在 object 字面值中应该有一个键时,它会计算括号内的表达式,然后在使用该表达式构造的 object 上定义一个属性。 For example, { ['foo']: 'bar' } results in { foo: 'bar' } .例如, { ['foo']: 'bar' }结果为{ foo: 'bar' } { ['a' + 'b']: 'bar' } results in { ab: 'bar' } . { ['a' + 'b']: 'bar' }结果为{ ab: 'bar' }

You can put any expression you want inside the [] brackets, and the result will be the key put on the object. For your case, you want the expression value of baseObject.val , so the syntax is [baseObject.val]: .您可以在[]括号内放置您想要的任何表达式,结果将是放在 object 上的键。对于您的情况,您需要baseObject.val的表达式值,因此语法为[baseObject.val]:

[ and ] are punctuators that have a different meaning in different contexts. []是标点符号,在不同的上下文中具有不同的含义。 Depending on where they appear, they might signify an array literal:根据它们出现的位置,它们可能表示数组文字:

let a = [];

or delimit a property name (aka "square bracket notation") where an expression is to be evaluated to get the property name:或分隔属性名称(又名“方括号表示法”),其中要计算表达式以获取属性名称:

let foo = 'log';
console[foo]('foo'); // equivalent to console.log('foo');

or define assignment of array values to variables:或定义数组值对变量的赋值:

let [a, b, c] = [1, 2, 3]

In the context of the OP, they delimit a computed property name , similar to the second example above:在 OP 的上下文中,它们分隔计算属性名称,类似于上面的第二个示例:

let x = 'foo';
let obj= {[x] : 'Foo'};

which creates an object as if by:它创建一个 object 就好像通过:

let obj = {foo: 'Foo'}; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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