javascript - 如何在不创建新条目的情况下将值插入子数组

标签 javascript arrays typescript multidimensional-array

所以我有这两个数组:

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/

相关文章:

javascript - 使用 jQuery 和 javascript 更改下拉列表中的选定值

javascript - 仅获取昨天和明天的日期,而不获取当天的日期和时间

arrays - 在同一文档 MongoDB 中将一个元素从一个数组移动到另一个数组

typescript - 类型 'T' 不满足约束 'string | number | symbol' 。类型 'T' 不可分配给类型 'symbol'

typescript - 递归函数中的基本情况不会停止递归 typescript

javascript - WebStorm + Nodemon 中的远程调试问题

javascript - 使用 ES6 将 javascript 中的对象数据数组转换为另一种形式

反转数组中元素的C++程序

javascript - Angular 2 中基于单选按钮禁用输入字段

javascript - 如何从下拉列表中获取选定的值?