如何重组数据以显示字符串在数组对象中出现多少次?

时间:2019-04-25 00:36:43

标签: javascript arrays reactjs chart.js

我正在尝试使用Chart.js创建四个饼图,这些饼图显示每个区域中出现的每个类别(I-IV)中的语言数量。换句话说,我想为一个类别I制作一个饼图,该饼图显示每个区域说出多少种类别I语言,而另一个类别则显示在每个区域说多少种第二类语言,等等。

我的数组元素如下:

const data = [
  {
    "category": "1",
    "language": "Danish",
    "weeks": "24",
    "hours": "600",
    "region": "Europe",
    "title": "World",
    "description": "Languages closely cognate with English"
  },
  {
    "category": "1",
    "language": "Dutch",
    "weeks": "24",
    "hours": "600",
    "region": "Europe",
    "title": "World",
    "description": "Languages closely cognate with English"
  },
  {
    "category": "1",
    "language": "French",
    "weeks": "30",
    "hours": "750",
    "region": "Europe",
    "title": "World",
    "description": "Languages closely cognate with English"
  },

...等等。某些语言包含多个区域,例如:

 {
    "category": "1",
    "language": "Spanish",
    "weeks": "24",
    "hours": "600",
    "region": ["Europe", "South America", "North America"],
    "title": "World",
    "description": "Languages closely cognate with English"
  }

我不确定执行此操作的最佳方法是什么。我是否需要创建一个新数组或以某种方式重新排列我的数据?任何帮助或建议,将不胜感激!

1 个答案:

答案 0 :(得分:0)

首先按每个类别过滤它,然后创建一个语言字符串数组。然后通过计数来制作具有每种语言外观的对象。

const categroy1data = data.filter(val => val.category === 1).map(val => val.language);
// => ['Danish', 'Dutch', 'Spanish' ... ]

const category1result = {}
category1data.forEach(val => {
  category1result[val] = 1 + (category1result[val] || 0)
})
// { 
//   Danish: 3,
//   Dutch: 2,
//   Spanih: 1,
// }