我正在尝试使用具有日期属性的对象来过滤 JSON 文件。我用它来过滤这个 JSON,通过具有日期和日期的属性分隔内容。之后我必须获取这个“部分”并再次过滤...但最大的问题是创建这个新的按日部分分组以再次过滤...
示例代码:
// this is the Data from the API just to simulate
const data =
[
{ date: "10/01/2023", id: 1 , whatever: "hi" },
{ date: "01/02/2023", id: 2 , whatever: "hello"},
]
// this is the allDates filtered that i get before from the JSON with no nulls and no duplicates
const dtList = ["10/01/2023", "01/02/2023"];
所以,现在我有这个例子,我之前用过(我在这里找到)按月过滤日期,但它只适用于月份:
var months = [
"Jan",
"Feb",
"Mar",
"Ap",
"May",
"Jun"
];
var ordered = {};
// this data come from the api for example
for (var i = 0, len = data.length; i < len; i++) {
var entry = data[i];
var m = entry.date.substring(0, 10);
if (m !== "") {
var mm = parseInt(m.split("/")[1]) - 1;
if (!ordered[months[mm]]) {
ordered[months[mm]] = [];
}
ordered[months[mm]].push(entry);
}
}
此代码创建一个对象,其中包含所有经过过滤并以月份分隔的数据, 所以之后我可以这样做:
//i filtered again with all the things i want and by date because ordered have subobjects separated by month...
ordered.Jan?.forEach((obj) => {
if (!isNaN(obj.nuParc)) {
nuParcJun += obj.nuParc;
setNuParcJun(nuParcJun);
}
// this code have some react too
我需要做同样的事情,但需要几天的时间。
//i was trying something near to this, but with no results untill now
dtList.forEach((value) => {
var dtsSep = Data.filter((obj) =>
obj.date.includes(value)
);
var ordered = {};
var ordered1 = Object.assign(ordered, dtsSep);
您必须将日期字符串解析为实际的“日期”对象,然后对数据进行分组,然后对每个组执行所需的操作,如下所示:
// Assuming `data` is your array of objects
const data = [
{ date: "10/01/2023", id: 1, whatever: "hi" },
{ date: "01/02/2023", id: 2, whatever: "hello" },
];
// Helper function to parse dates in DD/MM/YYYY format
function parseDate(dateString) {
const [day, month, year] = dateString.split('/');
return new Date(year, month - 1, day); // Note: months are 0-based
}
// Group data by day
const groupedByDay = data.reduce((acc, item) => {
const date = parseDate(item.date);
// Create a date string that includes the day for grouping
const dayKey = date.toISOString().split('T')[0]; // Format: YYYY-MM-DD
if (!acc[dayKey]) {
acc[dayKey] = [];
}
acc[dayKey].push(item);
return acc;
}, {});
console.log(groupedByDay);
// Now you can filter or manipulate data for each day
// Example: Iterate over each group and do something
Object.keys(groupedByDay).forEach(day => {
const items = groupedByDay[day];
// Perform your operations on `items`, which are all the entries for this `day`
console.log(`Processing items for day: ${day}`, items);
// Example operation: filter items based on some condition and do something with them
items.forEach(item => {
// Example condition: item.id is even
if (item.id % 2 === 0) {
console.log(`Even ID found: ${item.id}`);
// Perform your desired operation here
}
});
});
希望有帮助✌️