若后台返回格式如下:
let data = [
{"createdAt": "2020-08-02T11:00:24.580Z", "name": "西瓜"},
{"createdAt": "2020-08-03T11:00:24.580Z", "name": "水蜜桃"},
{"createdAt": "2020-08-03T11:00:24.580Z", "name": "樱桃"},
{"createdAt": "2020-08-02T11:00:24.580Z", "name": "西柚"},
]
1、将createdAt转换成日期格式
方法:使用 dayjs(createdAt).format('YYYY-MM-DD') 转换
注:dayjs 安装引用
npm install dayjs --save import dayjs from 'dayjs'
2、处理原数组
for ( let i=0; i<array.length; i++ ) {
let createdAt = dayjs(array[i].time);
array[i].createdAt = createdAt;
}
3、返回需要的数据格式 [{ createdAt: " ", location: [ ] }]
mapName (array) {
let newArray = [];
array.forEach((item, i) => {
let index = -1;
let alreadyExists = newArray.some((newItem, j) => {
if (item.createdAt === newItem.createdAt) {
index = j;
return true;
}
});
if (!alreadyExists) {
newArray.push({
createdAt: item.createdAt,
name: [item.name]
});
} else {
newArray[index].price.push(item.name);
}
});
return newArray;
}