【问题标题】:How to split an object that have dates, in another object, separating by year and month?如何将具有日期的对象拆分为另一个对象,按年和月分隔?
【发布时间】:2020-08-30 20:22:44
【问题描述】:

我正在尝试将 javascript 中的一组对象按年和月拆分为不同的对象。

有人可以指出如何处理此类问题的正确方向吗?

我从 api 得到的数据:

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
ano: "2020"
comprovante: "https://firebasestorage.googleapis.com/v0/b/dspsas-d0668.appspot.com/o/Storage%2FUser%2FbkrxhlxOCtY3kHUHlW9lnStIVlG2%2FComprovantes%2FxToy7.png?alt=media&token=d2184d68-f094-4c68-8a04-8c5e8e864559"
created_at: FirestoreTimestamp {_seconds: 1598723129, _nanoseconds: 75000000}
dataLancamento: FirestoreTimestamp {_seconds: 1598670000, _nanoseconds: 0}
dateArray: (3) ["29", "08", "2020"]
descricao: "lançamento"
dia: "29"
id: "3HCE8VxzBlV7GKsu89Ti"
mes: "08"
tags: (3) ["Tag", "teste", "Música"]
tipoLancamento: "Despesa"
user_id: "bkrxhlxOCtY3kHUHlW9lnStIVlG2"
valor: 1
__proto__: Object
1:
ano: "2020"
comprovante: null
created_at: FirestoreTimestamp {_seconds: 1598809946, _nanoseconds: 737000000}
dataLancamento: FirestoreTimestamp {_seconds: 1588302000, _nanoseconds: 0}
dateArray: (3) ["01", "05", "2020"]
descricao: "Teste"
dia: "01"
id: "EBHCwuc4w7Yum5H20C6u"
mes: "05"
tags: false
tipoLancamento: "Despesa"
user_id: "bkrxhlxOCtY3kHUHlW9lnStIVlG2"
valor: 5
__proto__: Object
2: {comprovante: null, valor: 1, created_at: FirestoreTimestamp, dataLancamento: FirestoreTimestamp, tipoLancamento: "Entrada", …}

我想要这样的东西:

object:
{
    0: {
        year: 2019,
        months: {
            0: {...obj}
            1: {...obj}
            2: {
                month: 'mar',
                items: {
                    0: {...item},
                    1: {...item},
                }
            }
        }
    }
}

【问题讨论】:

标签: javascript arrays sorting object


【解决方案1】:

NB 从移动设备进行日志记录,因此格式和语法可能有点不正确。此外,您似乎对 js 对象和数组不熟悉,因此请保持简单,以便您了解发生了什么。

const yourArray = [
   { ...dateArray: [...]},
   { ...dateArray: [...]},
   { ...dateArray: [...]}
];

var monthNames = [‘January’...];

function groupBy(objectArray, property) {
       return objectArray.reduce((acc, obj) => {
      const year = obj[property][2];
      if (!acc[year]) {
         acc[year] = [];
      }
      var month = monthNames[obj[property][1]];
      if(!acc[year][month]){
          acc[year][month] = [];
      }
      // Add object to list for given key's value
      acc[year][month].push(obj);
      return acc;
   }, {});
}
const grouped = groupBy(yourArray, 'dateArray');
console.log(grouped);

【讨论】:

  • 嗨@lucasPacheco 你觉得这个答案有帮助吗?您对此有任何疑问吗?
  • 我完成了一整天的工作,我刚刚开始尝试实施您的建议。经过一些修改以适应我的情况,它运行良好!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 2012-03-05
  • 2020-10-21
  • 2019-02-20
相关资源
最近更新 更多