filters = { 1: { stat: 'a' }, 2: { stat: 'b' }, 3: { stat: 'c'} }
delete filters[1]
Filters is now 2: { stat: 'b' }, 3: { stat: 'c'} }
, however we need the lowest key to equal 1, the 2nd lowest key to equal 2, and so on. In the example above, we deleted the lowest key, which requires renaming of keys. In the situation where we deleted key == 3
, obviously no renaming of keys would be required.
Order matters in the sense that, in the example above, key == 2
needs to be renamed to 1, and key == 3
then needs to be renamed to 2. key == 3
cannot simply be renamed to 1.
CodePudding user response:
Maybe consider using an array. The work will be a bit different, but will probably be what you want.
Note: It will start at 0, not at 1.
CodePudding user response:
If you want a collection of numeric indexed keys in sequential ascending order with easy rearrangement when a value is removed - then use an array, not an object.
const filters = [{ stat: 'a' }, { stat: 'b' }, { stat: 'c'}];
filters.splice(1, 1); // remove 1 item from index 1 of the array
console.log(filters);
// if you need to use the original structure somewhere too,
// transform it when needed:
const filtersObj = Object.fromEntries(
filters.map((obj, i) => [i 1, obj])
);
console.log(filtersObj);