首页 > 解决方案 > 如何将多个数据数组分组为 1 个数组

问题描述

我有一个列表数据

我期望:

[
    {
      "country_code": "US",
      "data": [3,3,3,3]
    },
    {
      "country_code": "VN",
      "data": [1,2,3,5]
    }
  ]

我为每个数组尝试了循环,但结果不是预期的。任何人都可以帮助我。谢谢!!!!

标签: javascript

解决方案


array.reduce()您可以使用and as来实现这一点array.forEach()

const data = [
    {
        time: 1,
        country:
        [
            { country_code: 'US', order_count: 11 },
            { country_code: 'CN', order_count: 21 },
            { country_code: 'VN', order_count: 31 }
        ]
    },
    {
        time: 2,
        country:
        [
            { country_code: 'US', order_count: 12 },
            { country_code: 'CN', order_count: 22 },
            { country_code: 'VN', order_count: 32 }
        ]
    },
    {
        time: 3,
        country:
        [
            { country_code: 'US', order_count: 13 },
            { country_code: 'CN', order_count: 23 },
            { country_code: 'VN', order_count: 33 }
        ]
    }
]

const mappedData = data.reduce((mdAcc, obj) => {
   obj.country.forEach((country) => {
      let obj = mdAcc.find((md) => md.country_code === country.country_code);
      if (!obj) {
        mdAcc.push({country_code: country.country_code, data: [country.order_count]});
      } else {
         obj.data.push(country.order_count);
      }
   })

   return mdAcc;
}, []);

推荐阅读