我有一個很長的日期物件,它將日期與價格/數??字配對。例如:
let obj = {
"2022-09-17": 45,
"2022-09-18": 35,
"2022-09-19": 34,
"2022-09-20": 26,
"2022-09-21": 25,
"2022-09-22": 33,
"2022-09-23": 56,
"2022-09-24": 39,
"2022-09-25": 49,
"2022-09-26": 25,
"2022-09-27": 25,
"2022-09-28": 25,
"2022-09-29": 33,
"2022-09-30": 42,
"2022-10-01": 28,
"2022-10-02": 38,
"2022-10-03": 35,
"2022-10-04": 25,
"2022-10-05": 25,
"2022-10-06": 31
}
將此物件重新組合為與日期相關并包含鍵/值的月份陣列的最佳方法是什么?
例如 - 像這個截圖:

我想按月份對鍵/值對進行分組,以便稍后回圈遍歷所有月份,以找到每個月的最低價格。
但首先,我想在幾個月內找出分解這個物體的最佳方法?
謝謝,
uj5u.com熱心網友回復:
通常,reduce是一個很好的解決方案
let object = {
"2022-09-17": 45,
"2022-09-18": 35,
"2022-09-19": 34,
"2022-09-20": 26,
"2022-09-21": 25,
"2022-09-22": 33,
"2022-09-23": 56,
"2022-09-24": 39,
"2022-09-25": 49,
"2022-09-26": 25,
"2022-09-27": 25,
"2022-09-28": 25,
"2022-09-29": 33,
"2022-09-30": 42,
"2022-10-01": 28,
"2022-10-02": 38,
"2022-10-03": 35,
"2022-10-04": 25,
"2022-10-05": 25,
"2022-10-06": 31
}
const objectMonth = Object
.keys(object)
.reduce((acc, key) => {
const date = new Date(key)
const month = date.toLocaleString('default', { month: 'long' })
acc[month] = acc[month] || []
acc[month].push({
date: key,
price: object[key]
})
return acc
}, {})
console.log(objectMonth)
uj5u.com熱心網友回復:
你可以做這樣的事情。
邏輯
- 回圈遍歷物件中的條目
- 將日期拆分為年、月和日。
- 用一些邏輯獲取月份名稱。
- 減少物件中的這個條目陣列。
let obj = {
"2022-09-17": 45,
"2022-09-18": 35,
"2022-09-19": 34,
"2022-09-20": 26,
"2022-09-21": 25,
"2022-09-22": 33,
"2022-09-23": 56,
"2022-09-24": 39,
"2022-09-25": 49,
"2022-09-26": 25,
"2022-09-27": 25,
"2022-09-28": 25,
"2022-09-29": 33,
"2022-09-30": 42,
"2022-10-01": 28,
"2022-10-02": 38,
"2022-10-03": 35,
"2022-10-04": 25,
"2022-10-05": 25,
"2022-10-06": 31,
};
const months = [
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december",
];
const splittedData = Object.entries(obj).reduce(
(acc, [dateStr, value]) => {
const [year, month, date] = dateStr.split("-");
if (!acc[months[ month - 1]]) {
acc[months[ month - 1]] = [];
}
acc[months[ month - 1]].push({ [dateStr]: value });
return acc;
},
{}
);
console.log(splittedData);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/504516.html
標籤:javascript 数组 排序 for循环 目的
下一篇:VUE資料物件獲取屬性/值
