如何使用前一个键的最后元素填充键值对中的空数组?
用前一个非空键的最后元素填充对象中的空数组
给定如下对象,需要将其中值为空数组的键,替换为前一个非空键对应数组的最后一个元素:
const myitems = { 'items1': [{first:true, second:false}, {first:true, second:true}], 'items2': [], // 应填充为 {first:true, second:true} 'items3': [], // 应填充为 {first:true, second:true} 'items4': [{first:true, second:false}, {first:true, second:true}], 'items5': [{first:false, second:true}], 'items6': [], // 应填充为 {first:false, second:true} 'items7': [{first:true, second:true}], }
解决方案
通过遍历对象的键(保持插入顺序),维护一个变量记录最近的有效元素,即可实现需求:
// 获取对象的键数组,确保遍历顺序与对象插入顺序一致 const keys = Object.keys(myitems); // 存储最近的非空数组最后一个元素 let lastValidItem = null; for (const key of keys) { const currentValue = myitems[key]; if (Array.isArray(currentValue)) { if (currentValue.length === 0) { // 空数组替换为最近的有效元素 myitems[key] = lastValidItem; } else { // 更新最近有效元素为当前数组的最后一项 lastValidItem = currentValue[currentValue.length - 1]; } } } console.log(myitems);
逻辑说明
- 利用
Object.keys()获取键数组,ES6及以上版本会保留对象的插入顺序,保证遍历顺序符合需求 - 遇到非空数组时,立即更新
lastValidItem为该数组的最后一个元素 - 遇到空数组时,直接用
lastValidItem替换空数组 - 若对象第一个键即为空数组,
lastValidItem会是null,可根据实际需求添加默认值处理逻辑
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

