我正在使用 JS、python 和來自開放 API 的數據開發我自己的項目。即使是像我這樣的新手,從 API 中獲取數據也不是那麼棘手。但是,我在將數據轉化為對我有用的信息時遇到了麻煩(像往常一樣)。
下面是我正在掙扎的一部分,
AA:array(60)
[
0:{A:2016-01-01, B:12}
1:{A:2016-02-01, B:122}
2:{A:2016-03-01, B:162}
3:{A:2016-04-01, B:129}
.
.
.
n:{A:20NN-NN-NN, B:923}
]
如您所見,它是一個包含許多對象的數組。每個對像都具有相同的屬性鍵 A,BA 是具有日期信息的文字,而 B 具有一些數值。我想做的是創建具有年份信息的新對象。換句話說,新對象具有所有相同的月份和日期信息,只有 A 中的年份不同。而 B 將是同年 B 的總和(對不起,我不擅長英語 ngl 的錯誤解釋)。所以上面的例子如下所示。
newAA: array(5)
[
0:{A:2016-01-01, B:numeric value(sum of all 2016's B in above example)}
1:{A:2017-01-01, B:numeric value(sum of all 2017's B in above example)}
2:{A:2018-01-01, B:numeric value(sum of all 2018's B in above example)}
3:{A:2019-01-01, B:numeric value(sum of all 2019's B in above example)}
4:{A:2020-01-01, B:numeric value(sum of all 2020's B in above example)}
]
老實說,這對我來說很棘手,我不知道如何處理它以使其成為我想要的如果您有這樣做的好主意,請告訴我,您的幫助將不勝感激。
謝謝閱讀!
使用Array#reduce
,您可以迭代數組,同時更新一個Map
where the year
is thekey
和一個對像是 the value
。
結果將是這個 Map 的值,它是一個分組對象的列表,其中year
包含A
原始數組中的第一個和 total B
:
const AA = [ {A:'2016-01-01', B:12}, {A:'2016-02-01', B:122}, {A:'2016-03-01', B:162}, {A:'2016-04-01', B:129} ];
const res = [...
AA.reduce((map, { A, B }) => {
const [year] = A.split('-');
const yearRecord = map.get(year);
if(yearRecord) yearRecord.B += B;
else map.set(year, { A, B })
return map;
}, new Map)
.values()
];
console.log(res);
編輯:使用對象的相同解決方案:
const AA = [ {A:'2016-01-01', B:12}, {A:'2016-02-01', B:122}, {A:'2016-03-01', B:162}, {A:'2016-04-01', B:129} ];
const res = Object.values(
AA.reduce((map, { A, B }) => {
const [year] = A.split('-');
const yearRecord = map[year];
if(yearRecord) yearRecord.B += B;
else map[year] = { A, B };
return map;
}, {})
);
console.log(res);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句