-1

as the title states, by removing certain items from the Object, the index sequence get's disorganized.

Let's say you have this Object:

var oObject = {
0:{"Name0":"Example0", "Number":13},
1:{"Name1":"Example1", "Number":13},
2:{"Name2":"Example2", "Number":13},
3:{"Name3":"Example3", "Number":13},
4:{"Name4":"Example4", "Number":13}
}

By removing [3] Index, with delete oObject[3] you get the following Object:

var oObject = {
0:{"Name0":"Example0", "Number":13},
1:{"Name1":"Example1", "Number":13},
2:{"Name2":"Example2", "Number":13},
4:{"Name4":"Example4", "Number":13}
}

as you can see oObject-Indexes got disorganized.

Question: Is there an operation that can delete entries from Objects and keep it clean in terms of indexes ?

1 Answers1

1

Since you have an array like object, you can convert it to an array using Array#from, then splice the resulting array with the given index and return the array in the original object form using Array#reduce:

var oObject = {
0:{"Name0":"Example0", "Number":13},
1:{"Name1":"Example1", "Number":13},
2:{"Name2":"Example2", "Number":13},
3:{"Name3":"Example3", "Number":13},
4:{"Name4":"Example4", "Number":13}
};

const delEntry = (oObject, idx) => {
 const arr = Array.from({...oObject, length: Object.keys(oObject).length});
 arr.splice(idx, 1);
 return arr.reduce((r, a, i) => { r[i] = a; return r; }, {});
}

console.log(delEntry(oObject, 3));

EDIT

As @VLAZ suggested in the comments, this can be done by directly using array method Array#splice on array like objects:

var oObject = {
0:{"Name0":"Example0", "Number":13},
1:{"Name1":"Example1", "Number":13},
2:{"Name2":"Example2", "Number":13},
3:{"Name3":"Example3", "Number":13},
4:{"Name4":"Example4", "Number":13}
};
const delEntry = (oObject, idx) => {
  const o = {...oObject, length: Object.keys(oObject).length};
  Array.prototype.splice.call(o, idx, 1);
  const {length, ...rest} = o;
  return rest;
}
console.log(delEntry(oObject, 3))
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • You can directly splice items out of an object, so no need for a conversion to an array and back. Array methods are generic exactly so you can execute them on non-arrays. – VLAZ Oct 23 '20 at 16:06