gpt4 book ai didi

javascript 迭代和重新映射

转载 作者:行者123 更新时间:2023-12-03 03:21:08 24 4
gpt4 key购买 nike

我有一个如下所示的数据集:

const data = [["customer1",29349,3654],["customer2",29349,3654],["customer3",15178,130]

我需要使用 map 将数据转换为此。

series: [{
category: 'Resolved before conciliation',
data: [29349, 29349, 15178]
}, {
category: 'Conciliation successful',
data: [3654, 29349, 130]
}]

我尝试了以下方法,这让我获得了第一个类别,但我似乎无法弄清楚如何将第二个类别添加到同一张 map 中的系列中。

const series = [{
name: 'Resolved before conciliation',
data: data.map(([...data]) => (data[1]))
}]

console.log(JSON.stringify(series))

输出:

[{"name":"Resolved before conciliation","data":[29349,29349,15178]}]

最佳答案

使用reduce分组:

const data = [["customer1",29349,3654],["customer2",29349,3654],["customer3",15178,130]];

let reduced = data.reduce((results, arr) => {
results[0].data.push(arr[1]);
results[1].data.push(arr[2]);
return results;
}, [{ category: 'Resolved before conciliation', data : [] }, { category: 'Conciliation successful', data : [] }]);

console.log(reduced);

关于javascript 迭代和重新映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com