如何使用Javascript将迭代器索引号附加到数组中的每个项目?

时间:2014-12-27 20:08:12

标签: javascript jquery arrays angularjs iterator

如何附加一个名为'Index'的键,其值为下面数组的词典索引?在此之前,数组应按时间戳排序,以便TimeStamp:111首先出现,TimeStamp:222出现在第二个等等。

例如,请参阅下面的原始数组

items = [
            {Id: "01", Name: "A", Price: "1.00", Quantity: "1",TimeStamp:111},
            {Id: "02", Name: "B", Price: "10.00", Quantity: "1",TimeStamp:222},
            {Id: "04", Name: "C", Price: "9.50", Quantity: "10",TimeStamp:434},
            {Id: "03", Name: "a", Price: "9.00", Quantity: "2",TimeStamp:545},
            {Id: "06", Name: "b", Price: "100.00", Quantity: "2",TimeStamp:676},
            {Id: "05",Name: "c", Price: "1.20", Quantity: "2",TimeStamp:777}
        ];

生成的数组应如下所示:

items = [
    {Id: "01", Name: "A", Price: "1.00", Quantity: "1",TimeStamp:111,Index:1},
            {Id: "02", Name: "B", Price: "10.00", Quantity: "1",TimeStamp:222,Index:2},
            {Id: "04", Name: "C", Price: "9.50", Quantity: "10",TimeStamp:434,Index:3},
            {Id: "03", Name: "a", Price: "9.00", Quantity: "2",TimeStamp:545,Index:4},
            {Id: "06", Name: "b", Price: "100.00", Quantity: "2",TimeStamp:676,Index:5},
            {Id: "05",Name: "c", Price: "1.20", Quantity: "2",TimeStamp:777,Index:6}
        ];

这是我的尝试:http://jsfiddle.net/chrisguzman/f7dnfrjf/ 我已经弄清楚如何将一个项目附加到每个字典,但不知道如何附加其各自的迭代器。

此外,这里是角度js(奖励点,如果有办法用角度):http://codepen.io/chriscruz/pen/GgjGvO?editors=101

2 个答案:

答案 0 :(得分:2)

索引从0开始,因此您需要为每个索引添加+1,例如

items.forEach(function (d, index) {
    d.Index = index + 1;
});

演示:http://jsfiddle.net/f7dnfrjf/1/

Angular demos:

  1. http://codepen.io/pen/ZYpRag - 索引显示为2,3,5,6

  2. http://codepen.io/pen/zxKapG - 索引显示为1,2,3,4

答案 1 :(得分:1)

运行时系统将3个参数传递给.forEach():第一个是数组元素,第二个是索引,第三个是数组本身。

因此:

items.forEach(function (d, i) {
    d.Index = i;
});