如何按日期对Flutter中实时数据库转换的Map数据排序?
按时间先后顺序排序实时数据库获取的Map订单
当前数据结构
从实时数据库获取并转换为Map的数据如下:
{ "Table 2": { "order 1": { "WATER": { "price": 1.50, "quantity": 2 }, "date": "2022-12-14 17:34:51.428972" } }, "Table 1": { "order 2": { "date": "2022-12-14 17:35:04.761532", "COCA COLA": { "price": 2, "quantity": 1 } }, "order 1": { "DAISY": { "price": 7, "quantity": 1 }, "date": "2022-12-14 17:22:12.678864", "4 CHEESES": { "price": 7, "quantity": 1 }, "WATER": { "price": 1.50, "quantity": 2 } } } }
期望排序结果
需要将所有订单按日期的时间先后顺序排序,最终结构如下(注:由于对象属性无序,这里用数组承载排序后的条目以保证顺序稳定):
[ { "Table 1": { "order 1": { "DAISY": { "price": 7, "quantity": 1 }, "date": "2022-12-14 17:22:12.678864", "4 CHEESES": { "price": 7, "quantity": 1 }, "WATER": { "price": 1.50, "quantity": 2 } } } }, { "Table 2": { "order 1": { "WATER": { "price": 1.50, "quantity": 2 }, "date": "2022-12-14 17:34:51.428972" } } }, { "Table 1": { "order 2": { "date": "2022-12-14 17:35:04.761532", "COCA COLA": { "price": 2, "quantity": 1 } } } } ]
实现方案
步骤说明
- 扁平化数据:遍历原始对象,提取每个订单的表名、订单名、日期及详情,统一存入数组。
- 按日期排序:将数组元素通过日期字符串转换为时间对象,比较时间戳实现升序排序。
- 重组结构:将排序后的数组元素转换为期望的嵌套对象格式,用数组承载以保证顺序。
示例代码
// 原始数据 const originalData = { "Table 2": { "order 1": { "WATER": { "price": 1.50, "quantity": 2 }, "date": "2022-12-14 17:34:51.428972" } }, "Table 1": { "order 2": { "date": "2022-12-14 17:35:04.761532", "COCA COLA": { "price": 2, "quantity": 1 } }, "order 1": { "DAISY": { "price": 7, "quantity": 1 }, "date": "2022-12-14 17:22:12.678864", "4 CHEESES": { "price": 7, "quantity": 1 }, "WATER": { "price": 1.50, "quantity": 2 } } } }; // 扁平化处理 const flattenedOrders = []; for (const table in originalData) { const orders = originalData[table]; for (const orderKey in orders) { const order = orders[orderKey]; flattenedOrders.push({ tableName: table, orderKey: orderKey, date: order.date, orderDetails: order }); } } // 按时间排序 flattenedOrders.sort((a, b) => new Date(a.date) - new Date(b.date)); // 重组为目标结构 const sortedResult = flattenedOrders.map(item => ({ [item.tableName]: { [item.orderKey]: item.orderDetails } })); console.log(JSON.stringify(sortedResult, null, 2));
注意点
- 不要依赖JavaScript对象的属性顺序来存储排序结果,因为不同环境对对象属性顺序的处理可能有差异,用数组承载能确保排序后的顺序稳定。
- 示例中的日期字符串格式能被
new Date()正确解析,若你的日期格式不同,需要调整日期转换逻辑。
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

