【问题标题】:Mapping an array of objects to dictionary in typescript将对象数组映射到打字稿中的字典
【发布时间】: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


【解决方案1】:

我认为你在跳跃这样的事情:

let data = [
  {id: 1, country: 'Germany', population: 83623528},
  {id: 2, country: 'Austria', population: 8975552},
  {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(item => [item.id, {country: item.country, population: item.population}]));

console.log(dictionary);

【讨论】:

  • 这里没有id。对于每个id,都有一个country 和population
  • 立即查看。这是预期的输出吗?
【解决方案2】:

您可以尝试使用Object.fromEntries(假设您的值需要是一个对象以同时保留country 和population):

let data = [
    {id: 1, country: 'Germany', population: 83623528},
    {id: 2, country: 'Austria', population: 8975552},
    {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(({id,...rest})=> ([id, rest]) ));

console.log(dictionary);

或者如果你想返回一个没有键的数组:

let data = [
    {id: 1, country: 'Germany', population: 83623528},
    {id: 2, country: 'Austria', population: 8975552},
    {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(({id,...rest})=> ([id, Object.values(rest)]) ));

console.log(dictionary);

【讨论】:

  • 我收到一个错误TS2339: Property 'fromEntries' does not exist on type 'ObjectConstructor'.
【解决方案3】:

你快到了,你需要为id构建一个对象,并使用rest参数

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(({
  id,
  ...rest
}) => ({
  [id]: rest
})));

console.log(dictionary)

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2016-11-22
    • 1970-01-01
    • 2018-06-18
    • 2021-01-09
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多