I have a very long object of dates, which pairs a date with a price/number. For example:
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
}
What is the best way to regroup this object as an array of months, which correlate to the dates and contain the key/values?
Eg - like this screenshot:
I want to group the key/value pair by months, so I can later, then loop through all months, to find the lowest price of each month.
But first, I wanted to figure out the best way to break up this object, in months?
Thanks,
CodePudding user response:
As often, reduce is a good solution here
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)
CodePudding user response:
You can do something like this.
Logic
- Loop through the entries in object
- Split the date into year, month and date.
- Get the month name with some logic.
- Reduce this array of entries in the object.
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);