Numeric order of keys of object re arrange from 0 javascript

Viewed 57
    var obj = {
      0 : 'value 0',
      1 : 'value 1',
      2 : 'value 2',
      3 : 'value 3',
      4 : 'value 4'
    }

delete obj[2];

on performing above action its deleting the key value pair with the key 2. up to here its fine. But what I want is I want is it gives the out put keys as 0 1 3 4 but I want to re arrange the keys like 0 1 2 3.

5 Answers

Cause its an array of elements I offer you using arrays. If you delete an item from it, it will change the key automatically. For Example:

var a = [
     'value 0',
     'value 1',
     'value 2',
     'value 3',
     'value 4',
]
a[2].pop()

You could take the values of the object, and while the keys are positive 32 bit integers, which vould be indives of an array, you could assign this array to an object and get a new object with new keys.

Method used:

var object = { 0: 'value 0', 1: 'value 1', 2: 'value 2', 3: 'value 3', 4: 'value 4' }

delete object[2];

object = Object.assign({}, Object.values(object));

console.log(object);

You can do something like this, Loop the source array after delete and recreate its key.

window.onload = function(){

 var obj = {
      0 : 'value 0',
      1 : 'value 1',
      2 : 'value 2',
      3 : 'value 3',
      4 : 'value 4'
    }

console.log(obj);

delete obj[2];

reIndexArray(obj);

function reIndexArray(fromArray)
{
  var startIndex = 0;
  var toArray = {};

  for(var key in fromArray)
  {
    toArray[startIndex] = obj[key];
    startIndex++
  }
  
  console.log(toArray);
}






}

You can change it into the Array with Object.values and use .splice method. If your object has the length, you can use Array.from method instead of Object.values.

var obj = {
    0 : 'value 0',
    1 : 'value 1',
    2 : 'value 2',
    3 : 'value 3',
    4 : 'value 4'
};

var arr = Object.values(obj);
console.log(arr); // ['value 0', 'value 1', 'value 2', 'value 3', 'value 4']

// Remove a value of key 2.
arr.splice(2, 1); // splice(from[, amount[, ...values to push]])
console.log(arr); // ['value 0', 'value 1', 'value 3', 'value 4']

// If you want to return into the original object, you can use `Object.assign`.
Object.assign(obj, arr);
console.log(obj); // {0: 'value 0', 1: 'value 1', 2: 'value 3', 3: 'value 4', 4: 'value 4'}

// There is no value of key 5 in arr. So Object.assign can't replace the key 5. You have to delete it.
delete obj[4];
console.log(obj); // {0: 'value 0', 1: 'value 1', 2: 'value 3', 3: 'value 4'}

You could also use a Map instead of a regular object. Depends on your use case though.

const map = new Map([[0, 'value0 '],[1, 'value1 '],[2, 'value2']]);

map.delete(1)

const values = [...map.values()];

const newMap = new Map(values.map((value, index) => [index, value]))
Related