我正在Angular中调用Api并将数据显示在Angular 7中的mat-table上。
响应就是这样
{
"promo": "Mon",
"start": "2019",
"carrier": "[UPS Ground, UPS Express, UPS Expedited]",
"end": "2020",
"shipTime": "[10, 2Day, Overnight]",
"price": "[0.0, 14.99, 24.99]",
}
我正在这样的Mat Table上显示此数据
Mon|2019| [UPS Ground, UPS Express, UPS Expedited] | 2020 | [10, 2Day, Overnight]| [0.0, 14.99, 24.99]
But i want to display it like this
Mon | 2019 | UPS Ground | 2020 |10 | 0.0
Mon | 2019 | UPS Express | 2020 |2day| 14.99
Mon | 2019 | UPS Expedited | 2020 | Overnight | 24.99
我可以指向任何建议,链接或教程吗?我到处搜寻,找不到任何东西。
谢谢
答案 0 :(得分:1)
您必须自己重新格式化数据,最好是在最初获取数据的Angular服务中。
假设承运人,shipTime和price数组的长度始终相等,并以相应的顺序排列,则下面的方法应该起作用。
const newResp = [];
resp.forEach(promo => {
promo.carrier.forEach((carrier, i) => {
const shipTime = promo.shipTime[i];
const price = promo.price[i];
newResp.push({ ...promo, carrier, shipTime, price });
});
});
return newResp;
此代码在newResp列表中为每个促销中的每个运营商创建一个新条目。如果促销活动没有任何运营商,则不会为该促销活动创建任何条目。
答案 1 :(得分:1)
假设carrier
price
和shipTime
具有相同的长度。现在,您可以遍历modifiedInput
以显示在表格中。
const input = [{
"promo": "Mon",
"start": "2019",
"carrier": ['UPS Ground', 'UPS Express', 'UPS Expedited'],
"end": "2020",
"shipTime": ['10', '2Day', 'Overnight'],
"price": ['0.0', '14.99', '24.99']
},{
"promo": "Tue",
"start": "2019",
"carrier": 'UPS Ground',
"end": "2020",
"shipTime": 'Overnight',
"price": '14.99'
}];
const modifiedInput = input.reduce((output, item) => {
if(item.carrier instanceof Array) {
item.carrier.forEach((carrier, index) => {
output.push({
...item,
carrier,
shipTime: item.shipTime[index],
price: item.price[index]
});
});
} else {
output.push(item);
}
return output;
}, []);
console.log(modifiedInput);
.as-console-wrapper {
max-height: 100% !important;
}