11

For example:

var Cars = {
    1: { "Make": "Honda",
         "Model": "Accord",
         "Color": "Red"
    },
    2: { "Make": "Honda",
         "Model": "Civic",
         "Color": "Silver"
    },
    3: { "Make": "Honda",
         "Model": "Jazz",
         "Color": "Yellow"
    }

If I do a delete.Cars[2]; I will be left with Cars[1] and Cars[3].

I need a way (JS or jQuery) so that when I delete a key, the object reindexes. So, in the example above, I'm left with Cars[1] and Cars[2] (which was Cars[3]).

joedborg
  • 17,651
  • 32
  • 84
  • 118

2 Answers2

7

That is because you dont need the keys for the array.

var Cars = [
    {
        "Make": "Honda",
        "Model": "Accord",
        "Color": "Red"
    },{
        "Make": "Honda",
        "Model": "Civic",
        "Color": "Silver"
    },{
        "Make": "Honda",
        "Model": "Jazz",
        "Color": "Yellow"
    }
];

alert(Cars[1]['Make']); // Honda
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
  • But if I have array like this [ {key:"label", sortable:true, resizeable:true}, {key:"notes", sortable:true,resizeable:true},...... After shift it starts at second param. With index = 1 – fdrv Mar 16 '16 at 23:13
4

You can have a look at this:

Array: Javascript - Reindexing an array

Object: Algorithm to re-index an array of objects after insertion or drag 'n' drop order change

It should do the trick :)

Referencing other developers in this thread, and myself, it will be better to use an Array.

Community
  • 1
  • 1
Marc Uberstein
  • 12,501
  • 3
  • 44
  • 72
  • 1
    Not. Stop using them and use Array instead. (Well, in fact, it can help, if you do `Array.prototype.splice.call(theStrangeObject, 2, 1)` instead of `delete theStrangeObject[2]`... but no, it does not help, you have no `length` there. Use Array). –  Nov 29 '11 at 12:17