javascript - json数组迭代并从json数组中创建自己的数组列表
问题描述
查看 json 数组,然后...
[
{
"country" : "Bangladesh",
"deathInLastWeek" : [40, 42, 45, 50, 55, 60, 65],
"maxDeath" : 82,
"minDeath" : 5
},
{
"country" : "India",
"deathInLastWeek" : [100, 110, 95, 102, 89, 120, 98],
"maxDeath" : 148,
"minDeath" : 19
},
{
"country" : "England",
"deathInLastWeek" : [56, 62, 120, 56, 98, 91, 87],
"maxDeath" : 124,
"minDeath" : 13
}
]
上面的 json 数组迭代所有字段并将这些字段呈现在列表中。然后将如下所示的两个数组设置为输出。
const dataMin = [
{ name: "Bangladesh", value: 5 },
{ name: "India", value: 19 },
{ name: "England", value: 13 }
];
const dataMax = [
{ name: "Bangladesh", value: 82 },
{ name: "India", value: 148 },
{ name: "England", value: 124 }
];
解决方案
我使用reduce解决了这个问题
const dataMin = data.reduce((acc, item) => {
acc.push({ name: item.country, value: item.minDeath });
return acc;
}, []);
const dataMax = data.reduce((acc, item) => {
acc.push({ name: item.country, value: item.maxDeath });
return acc;
}, []);
推荐阅读
- laravel - 随机频道名称上的 Laravel 广播
- oracle - Oracle Pro*C 对象类型转换为 C 结构
- mysql - 为什么我这里不需要给独立的新表起个名字?
- css - 如何在字体图标中转换图标
- postgresql - 具有未知列数的 Postgres 数据库表
- ldap - 将 LDAP 身份验证添加到 html 静态站点
- graphql - In a GraphQL schema documentation comment, how do you link to a type?
- javascript - React JS:TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。接收类型未定义
- php - SYMFONY 序列化器 - 格式错误的 UTF-8 字符,可能编码不正确
- python-3.x - 连接 http 网关服务器到 Python Pyro 的名称服务器的示例