基于对象数组与日期标签生成补全缺失日期的新数组
生成包含所有日期标签的数组(补全缺失默认值)
需求:基于给定的日期标签数组dailyLabels生成新数组,新数组需包含dailyLabels的所有日期条目。若dailyCurr中存在对应日期的条目则直接使用,不存在则用指定默认值填充(mov_date为空字符串、value为0、cod为null、product为空字符串、year为"curr")。
给定数据
const dailyLabels = [ "01/11", "02/11", "03/11", "04/11" ] const dailyCurr = [ { mov_date: "2022-11-03T14:16:10.694Z", value: 2, cod: 5, product: "ODONTO", day: "03/11", year: "curr" }, { mov_date: "2022-11-04T14:16:10.694Z", value: 2, cod: 5, product: "ODONTO", day: "04/11", year: "curr" } ]
解决方案
基础实现(适用于小数据量)
先定义默认值对象,遍历dailyLabels并匹配dailyCurr中的条目:
const defaultItem = { mov_date: "", value: 0, cod: null, product: "", year: "curr" }; const thirdArray = dailyLabels.map(day => { // 查找对应日期的条目 const matchedItem = dailyCurr.find(item => item.day === day); // 找到则返回条目拷贝,否则返回带当前日期的默认值 return matchedItem ? { ...matchedItem } : { ...defaultItem, day }; });
优化实现(适用于大数据量)
将dailyCurr转换为Map以提升查找效率(时间复杂度从O(n)降至O(1)):
const defaultItem = { mov_date: "", value: 0, cod: null, product: "", year: "curr" }; // 构建以day为键的映射表 const currDayMap = new Map(dailyCurr.map(item => [item.day, item])); const thirdArray = dailyLabels.map(day => { const matchedItem = currDayMap.get(day); return matchedItem ? { ...matchedItem } : { ...defaultItem, day }; });
最终结果
执行上述代码后,thirdArray将与期望结果完全一致:
const thirdArray = [ { mov_date: "", value: 0, cod: null, product: "", day: "01/11", year: "curr" }, { mov_date: "", value: 0, cod: null, product: "", day: "02/11", year: "curr" }, { mov_date: "2022-11-03T14:16:10.694Z", value: 2, cod: 5, product: "ODONTO", day: "03/11", year: "curr" }, { mov_date: "2022-11-04T14:16:10.694Z", value: 2, cod: 5, product: "ODONTO", day: "04/11", year: "curr" } ]
内容的提问来源于stack exchange,提问作者devlpo
相关产品推荐
相关产品推荐

