gpt4 book ai didi

javascript - 将 json 响应转换为表

转载 作者:行者123 更新时间:2023-12-01 01:01:06 26 4
gpt4 key购买 nike

我正在尝试将 json 响应转换为接受我的表(来自 devextreme 的组件)的数组。我正在尝试在 Angular 6 上执行此操作。Json 看起来像这样:

"data": [
{
"type": "A",
"date": "2018-05",
"value": "153"
},
{
"type": "B",
"date": "2018-05",
"value": "888"
},
{
"type": "C",
"date": "2018-05",
"value": "999"
},
{
"type": "D",
"date": "2018-05",
"value": "555"
},
{
"type": "A",
"date": "2018-06",
"value": "148"
},
{
"type": "B",
"date": "2018-06",
"value": "222"
},
{
"type": "C",
"date": "2018-06",
"value": "555"
},
{
"type": "D",
"date": "2018-06",
"value": "666"
},
{
"type": "A",
"date": "2018-07",
"value": "156"
},
{
"type": "B",
"date": "2018-07",
"value": "111"
},
{
"type": "C",
"date": "2018-07",
"value": "333"
},
{
"type": "D",
"date": "2018-07",
"value": "999"
}
],
"number": "111-111"
}
]

我需要将其转换为这种格式:

[{
month: '2018-05',
A: 153,
B: 888,
C: 999,
D: 555
},
{
month: '2018-06',
A: 148,
B: 222,
C: 555,
D: 666
},
{
month: '2018-07',
A: 156,
B: 111,
C: 333,
D: 999
}]

类型的数量可以改变(例如,可能只有 A 和 B)。有人能帮我吗?我正在使用此组件在网站 https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/SimpleArray/Angular/Light/ 上呈现数据

最佳答案

这就是我解决您的问题的方法:

1) 从数据源获取类型和日期的列表。我们利用 JavaScript 的 Set存储值,以便值是唯一的(没有重复项)。

date 中的值将被视为结果数组中每个对象的唯一键,type 将是结果的其他属性('A '、'B'、'C' 和 'D')

2) 一旦我们有了这两个数组,我们将迭代原始列表来生成对象。属性 ABCD 的值通过过滤日期来填充code> 和原始 list 中的 type

const list = {"data":[{"type":"A","date":"2018-05","value":"153"},{"type":"B","date":"2018-05","value":"888"},{"type":"C","date":"2018-05","value":"999"},{"type":"D","date":"2018-05","value":"555"},{"type":"A","date":"2018-06","value":"148"},{"type":"B","date":"2018-06","value":"222"},{"type":"C","date":"2018-06","value":"555"},{"type":"D","date":"2018-06","value":"666"},{"type":"A","date":"2018-07","value":"156"},{"type":"B","date":"2018-07","value":"111"},{"type":"C","date":"2018-07","value":"333"},{"type":"D","date":"2018-07","value":"999"}],"number":"111-111"};

// const dates = [...new Set(list.data.map(item => item.date))];
const dates = Array.from(list.data.map(item => item.date));
console.log(dates);

// const types = [...new Set(list.data.map(item => item.type))];
const types = Array.from(list.data.map(item => item.type));
console.log(types)

const res = dates.map(date => {
const obj = {};
types.map(type => {
obj[type] = list.data.filter(item => item.date === date && item.type === type)[0].value;
});
obj.date = date;
return obj;
});
console.log(res);

关于javascript - 将 json 响应转换为表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56053369/

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