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

JavaScript中删除对象键后将剩余键重命名为连续序号的方法

实现对象键的连续重索引

要解决删除对象键后,将剩余键按原大小顺序重新映射为从1开始的连续数字的问题,你可以用以下方法实现:

核心思路

  1. 提取对象的所有键,转换为数字类型后按从小到大排序
  2. 遍历排序后的键,将对应的值重新赋值给从1开始的连续新键

通用实现函数

function reindexFilters(filters) {
  // 提取键并转为数字,确保按数值排序
  const sortedKeys = Object.keys(filters)
    .map(key => Number(key))
    .sort((a, b) => a - b);
  
  const newFilters = {};
  sortedKeys.forEach((originalKey, index) => {
    // 新键从1开始递增
    newFilters[index + 1] = filters[originalKey];
  });
  
  return newFilters;
}

使用示例

示例1:删除键1后的重索引

let filters = { 1: { stat: 'a' }, 2: { stat: 'b' }, 3: { stat: 'c'} };
delete filters[1];
filters = reindexFilters(filters);
console.log(filters); // 输出: {1: { stat: 'b' }, 2: { stat: 'c'}}

示例2:删除键3后的重索引

let filters = { 1: { stat: 'a' }, 2: { stat: 'b' }, 3: { stat: 'c'} };
delete filters[3];
filters = reindexFilters(filters);
console.log(filters); // 输出: {1: { stat: 'a' }, 2: { stat: 'b'}}

注意事项

  • 必须将键转为数字后再排序:因为Object.keys()返回的是字符串类型的键,如果直接对字符串排序,会出现'10'排在'2'前面的错误,转成数字才能保证正确的数值顺序。
  • 这个方法适用于任意数量的键,无论删除哪个位置的键,都能保证剩余值按原顺序映射到连续的数字键上。

内容的提问来源于stack exchange,提问作者Canovice

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:01:14