最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Reindex javascript arrayobject after removing a key - Stack Overflow

programmeradmin0浏览0评论

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

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 asked Nov 29, 2011 at 11:55 joedborgjoedborg 18.4k33 gold badges87 silver badges122 bronze badges 8
  • 6 Is there a reason you arent using an actual array? – Richard Dalton Commented Nov 29, 2011 at 11:57
  • If you use an array, this question has your answer- stackoverflow.com/questions/500606/… – Richard Dalton Commented Nov 29, 2011 at 12:01
  • Because you can't have multiple dimensions, I've just checked. – joedborg Commented Nov 29, 2011 at 12:01
  • But you haven't got multiple dimensions :D – Richard Dalton Commented Nov 29, 2011 at 12:02
  • 1 You can have an array of arrays, or an array of objects. (So wherever you checked didn't give all the information.) – nnnnnn Commented Nov 29, 2011 at 12:03
 |  Show 3 more comments

2 Answers 2

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论