在打字稿中将对象数组映射到字典

时间:2020-04-23 04:28:19

标签: javascript typescript dictionary collections hashmap

我正在尝试使用打字稿将对象数组映射到字典。 我编写了以下代码:

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
  }
}

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

您可以尝试使用SELECT * FROM table_a WHERE col_a||col_b NOT IN ( SELECT coalesce (col_a,'~')||coalesce (col_b , '~') from table_b ); (假设您的值必须是同时保留Object.fromEntriescountry的对象):

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);

答案 2 :(得分:1)

您快到了,您需要为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)