所以我有这两个数组:
resultList: { date: string, amount: number }[] = [];
dateList: { date: string, amounts: { amount: number }[] }[] = [];
其中一个有所有结果,我想按日期排序,因此是第二个数组。 这是我用来尝试实现此目的的代码:
this.resultList.forEach((result) => {
let dateFound: boolean = false;
this.dateList.forEach((date) => {
if (result.date === date.date) {
dateFound = true;
return;
}
});
if (dateFound == false) {
//create new date entry in dateList
this.dateList.push({date: result.date, amounts: []});
}
//find that date entry and push a value to it's sub array called amounts
this.dateList.find((dates) => {
return dates.date == result.date
}).amounts.push({
amount: result.amount
});
});
如果同一日期有 3 个结果,则输出
[
{date: '2018-03-21', amounts: [{amount: 1}]},
{date: '2018-03-21', amounts: [{amount: 1},{amount: 43}]},
{date: '2018-03-21', amounts: [{amount: 1},{amount: 43}, {amount: 55}]}
]
如果您在同一日期有 3 个结果,则需要输出
[
{date: '2018-03-21', amounts: [{amount: 1},{amount: 43}, {amount: 55}]}
]
最佳答案
您可以先通过 reducing 来完成此操作您的数据放入一个对象中,以唯一日期作为键,金额作为每个键的值,然后是 mapping将它们放入所需输出的结构中,如下所示:
var data = [
{date: '2018-03-21', amount: 1},
{date: '2018-03-21', amount: 43},
{date: '2018-03-21', amount: 41},
{date: '2018-03-22', amount: 18},
{date: '2018-03-23', amount: 25},
{date: '2018-03-24', amount: 15},
{date: '2018-03-24', amount: 25},
];
// reduce to single object with unique dates as keys, collection of amounts as values
var dateMap = data.reduce((res, curr) => {
// if the date has not been added already
if (!res[curr.date]) {
// create it on the result object
res[curr.date] = []
}
// push the amount into the array for the date
res[curr.date].push({amount: curr.amount});
return res;
}, {});
// map each key of dateMap to an object matching the desired output format
var dateList = Object.keys(dateMap).map(key => {
return {date: key, amounts: dateMap[key]};
});
console.log(dateList);
关于javascript - 如何在不创建新条目的情况下将值插入子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49409961/