javascript - 我想以特定方式转换对象数组
问题描述
我在处理图表时有一个场景,我需要将下面的对象数组转换为其他数组数组。
输入
const country = [
{"country": "Germany","visits": "306"},
{"country": "USA","visits": "106"},
{"country": "UK","visits": "206"},
];
所需的输出应如下所示:
[
["Country", "Visits"],
["Germany", 306],
["USA", 106],
["UK", 206]
]
我无法获得所需的输出。
解决方案
您需要做的就是将字段映射到数组。
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; }
推荐阅读
- azure - 如何在 azure API 管理之前使用 Azure 流量管理器
- c# - System.Drawing.dll 中发生“System.ArgumentException”,但未在用户代码中处理
- javascript - 得到一个'无法设置属性'onclick'错误'
- mysql - MYSQL:创建唯一索引以避免在许多条目显示0时出现重复条目
- c++ - 测量 C++ 中并发代码使用的内存消耗
- c++ - 从未排序的数组中删除重复项
- python - 在 Django 中使用旧数据库进行身份验证登录
- python - Clarifai:“格式错误或无效的请求”
- ef-core-2.0 - 实体框架核心重用一组包含语句
- php - Apache 2.4 PHP 7.0 和 7.2 在分离的虚拟主机上