You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用前一个键的最后元素填充键值对中的空数组?

用前一个非空键的最后元素填充对象中的空数组

给定如下对象,需要将其中值为空数组的键,替换为前一个非空键对应数组的最后一个元素:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:56:05