Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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]).

share|improve this question
4  
Is there a reason you arent using an actual array? – Richard Dalton Nov 29 '11 at 11:57
If you use an array, this question has your answer- stackoverflow.com/questions/500606/… – Richard Dalton Nov 29 '11 at 12:01
Because you can't have multiple dimensions, I've just checked. – jdborg Nov 29 '11 at 12:01
But you haven't got multiple dimensions :D – Richard Dalton Nov 29 '11 at 12:02
You can have an array of arrays, or an array of objects. (So wherever you checked didn't give all the information.) – nnnnnn Nov 29 '11 at 12:03
show 3 more commentsadd comment (requires an account with 50 reputation)

2 Answers

up vote 2 down vote accepted

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
share|improve this answer
Thanks! This works perfectly with splice. – jdborg Nov 29 '11 at 12:32
add comment (requires an account with 50 reputation)

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.

share|improve this answer
I saw that, will it work with objects like this? – jdborg Nov 29 '11 at 12:03
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). – herby Nov 29 '11 at 12:17
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.