首页 > 解决方案 > 我想以特定方式转换对象数组

问题描述

我在处理图表时有一个场景,我需要将下面的对象数组转换为其他数组数组。

输入

const country = [
  {"country": "Germany","visits": "306"},
  {"country": "USA","visits": "106"},
  {"country": "UK","visits": "206"},
];

所需的输出应如下所示:

[
          ["Country", "Visits"],
          ["Germany", 306],
          ["USA", 106],
          ["UK", 206]
]

我无法获得所需的输出。

标签: javascriptarraysobject

解决方案


您需要做的就是将字段映射到数组。

const countries = [
  { "country": "Germany", "visits": "306" },
  { "country": "USA",     "visits": "106" },
  { "country": "UK",      "visits": "206" },
];

console.log(countries.map(country => [ country.country, country.visits ]));
.as-console-wrapper { top: 0; max-height: 100% !important; }

如果您想要所有值,只需使用Object.values.

const countries = [
  { "country": "Germany", "visits": "306" },
  { "country": "USA",     "visits": "106" },
  { "country": "UK",      "visits": "206" },
];

console.log(countries.map(country => Object.values(country)));
.as-console-wrapper { top: 0; max-height: 100% !important; }


推荐阅读