[英]How to Set a Javascript Object Key to Be Another Object's Value
I have an Javascript object called person
with various properties such as id
, name
, phone
, etc.我有一个 Javascript
person
被叫人,具有各种属性,如id
、 name
、 phone
等。
I want to create a new Javascript object called roster that is just the name.我想创建一个名为 roster 的新 Javascript object,这只是名称。 Something like this:
是这样的:
let person = { name: "Hilda", "id": 123, "phone": 000-000-0000 };
let roster = { person.name : person.phone };
However, React throws an error having person.name
in the key.但是,React 抛出一个错误,其中
person.name
键。 It doesn't matter if I do person.name
or person["name"]
.我做
person.name
还是person["name"]
都没关系。 I have to do:我要做:
let roster = {};
roster[person.name] = person.phone;
Is there some special syntax to allow person.name
to be set as the key directly, or is the work-around required?是否有一些特殊的语法允许将
person.name
直接设置为键,或者是否需要解决方法?
Use []采用 []
let person = { name: "Hilda", "id": 123, "phone": "000-000-0000" }; let roster = { [person.name]: person.phone }; console.log(roster)
Vugar's answer is correct, this can be done by placing brackets []
around the first object's property name. Vugar 的回答是正确的,这可以通过在第一个对象的属性名称周围放置方括号
[]
来完成。
This is called a computed property name .这称为计算属性名称。 From the MDN web docs:
来自 MDN web 文档:
The object initializer syntax also supports computed property names.
object 初始化语法也支持计算属性名。 That allows you to put an expression in brackets [], that will be computed and used as the property name.
这允许您将表达式放在方括号 [] 中,该表达式将被计算并用作属性名称。 This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.
这让人想起属性访问器语法的括号表示法,您可能已经使用它来读取和设置属性。
Now you can use a similar syntax in object literals, too:
现在您也可以在 object 文字中使用类似的语法:
// Computed property names
let i = 0;
const a = {
[`foo${++i}`]: i,
[`foo${++i}`]: i,
[`foo${++i}`]: i,
};
console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3
const items = ["A", "B", "C"];
const obj = {
[items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"
const param = 'size';
const config = {
[param]: 12,
[`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,
};
console.log(config); // {size: 12, mobileSize: 4}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.