我正在使用 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)}
]
老實說,這對我來說很棘手,我不知道如何處理它以使其成為我想要的如果您有這樣做的好主意,請告訴我,您的幫助將不勝感激。
謝謝閱讀!
uj5u.com熱心網友回復:
使用Array#reduce,您可以迭代陣列,同時更新一個Mapwhere the yearis 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361229.html
標籤:javascript 数组 目的
上一篇:使用VBA決議JSON物件和集合
下一篇:JQ根據鍵值獲取唯一的物件和陣列
