本文介绍一
种遍历对象键值对的方法,将值为空数组的字段,自动填充为前一个非空键中数组的最后一个元素,适用于数据补全、状态延续等场景。
在实际开发中,我们常遇到结构化数据中部分字段暂未赋值(如空数组 []),但业务逻辑要求其继承前一个有效状态的情形。例如,在表单步骤、时间序列状态快照或配置继承等场景下,需将空值“向前回填”为最近一次出现的有效值。
以下是一个简洁可靠的解决方案:
let lastValue = null;
for (const key in myitems) {
if (Array.isArray(myitems[key]) && myitems[key].length === 0) {
// 当前值为空数组,且已有有效 lastValue,则填充
if (lastValue !== null) {
myitems[key] = [lastValue];
}
} else if (Array.isArray(myitems[key]) && myitems[key].length > 0) {
// 更新 lastValue:取当前非空数组的最后一个元素
lastValue = myitems[key][myitems[key].length - 1];
}
// 忽略非数组类型值(增强鲁棒性)
}✅ 关键设计说明:
⚠️ 注意事项:
执行后,示例数据将变为:
{
'items1': [{first:true, second:false}, {first:true, second:true}],
'items2': [{first:true, second:true}], // ← 回填自 items1 最后一项
'items3': [{first:true, second:true}], // ← 继续沿用
'items4': [{first:true, second:false}, {first:true, second:true}],
'items5': [{first:false, second:true}],
'items6': [{first:false, second:true}], // ← 回填自 items5 唯一项
'items7': [{first:true, second:true}]
}该方法时间复杂度为 O(n),空间复杂度为 O(1),简洁高效,适合嵌入数据预处理流水线。