【发布时间】:2020-08-06 07:34:52
【问题描述】:
我正在尝试使用打字稿将对象数组映射到字典。 我写了以下代码:
let data = [
{id: 1, country: 'Germany', population: 83623528},
{id: 2, country: 'Austria', population: 8975552},
{id: 3, country: 'Switzerland', population: 8616571}
];
let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country})));
我得到如下输出:
{1: "Germany", 2: "Austria", 3: "Switzerland"}
我也想在输出中获取人口,为此我正在更改以下代码,但它给出了语法错误:
let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country, x.population})));
所需的输出类似于以下:
{
"1": {
"country": "Germany",
"population": 83623528
},
"2": {
"country": "Austria",
"population": 8975552
},
"3": {
"country": "Switzerland",
"population": 8616571
}
}
【问题讨论】:
-
您的预期输出是什么? - 您粘贴的不是有效的 javascript 对象
-
你缺少一个键,预期的输出不是一个有效的对象
-
问题中提到的
Desired output在语法上是错误的。
标签: javascript typescript dictionary collections hashmap