Javascript 如何将多个数据数组分组为一个数组

Javascript 如何将多个数据数组分组为一个数组,javascript,Javascript,我希望: [ { "country_code": "US", "data": [3,3,3,3] }, { "country_code": "VN", "data": [1,2,3,5] } ] 我尝试对每个数组进行循环,但结果不符合预期。谁来帮帮我。谢谢 这很明显。不需要愚蠢的循环。给你:

我希望:

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

我尝试对每个数组进行循环,但结果不符合预期。谁来帮帮我。谢谢

这很明显。不需要愚蠢的循环。给你:

var 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 }
        ]
    }
]

// suppose data[0] contains all country codes
const all_country_codes = (data) => 
    data[0].country.map(c => c.country_code); 

const get_order_count = (data, code) => 
    data.country.filter(d => d.country_code == code)[0].order_count;

const get_all_order_counts = (data, code) => 
    data.map(d => get_order_count(d, code))

const make_node = (data, code) => 
    ({ country_code:code, data:get_all_order_counts(data, code) })

const output = (data) => 
    all_country_codes(data).map(code => make_node(data, code));

console.log(output(data));
输出:

[
  { country_code: 'US', data: [ 11, 12, 13 ] },
  { country_code: 'CN', data: [ 21, 22, 23 ] },
  { country_code: 'VN', data: [ 31, 32, 33 ] }
]

您可以使用
array.reduce()
array.forEach()
实现这一点,如下所示:

const数据=[
{
时间:1,,
国家:
[
{国家代码:“美国”,订单数量:11},
{国家代码:'CN',订单数量:21},
{国家代码:'VN',订单计数:31}
]
},
{
时间:2,,
国家:
[
{国家代码:“美国”,订单数量:12},
{国家代码:'CN',订单数量:22},
{国家代码:'VN',顺序计数:32}
]
},
{
时间:3,,
国家:
[
{国家代码:“美国”,订单数量:13},
{国家代码:'CN',订单数量:23},
{国家代码:'VN',订单计数:33}
]
}
]
const mappedData=data.reduce((mdAcc,obj)=>{
obj.country.forEach((国家)=>{
让obj=mdAcc.find((md)=>md.country\u代码===country.country\u代码);
如果(!obj){
mdAcc.push({country\u代码:country.country\u代码,数据:[country.order\u count]});
}否则{
对象数据推送(国家/地区订单计数);
}
})
返回mdAcc;
}, []);