首页 > 解决方案 > 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 }
];

标签: javascriptjson

解决方案


我使用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;
}, []);


推荐阅读