简体   繁体   English

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

[英]How to append an iterator index number to each item within an array with Javascript?

How do you append a key called 'Index' with a value being the dictionaries index to the below array? 如何附加一个名为“Index”的键,其值为下面数组的词典索引? The array should be sorted by Timestamp before this occurs so that TimeStamp:111 comes first and TimeStamp:222 comes second, etc. 在此之前,数组应按时间戳排序,以便TimeStamp:111首先出现,TimeStamp:222出现在第二个等等。

For example, see below for original array 例如,请参阅下面的原始数组

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}
        ];

The resulting array should look like this: 生成的数组应如下所示:

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}
        ];

Here's my attempt: http://jsfiddle.net/chrisguzman/f7dnfrjf/ I've figured out how to append an item to each dictionary, but not how to append its respective iterator. 这是我的尝试: http//jsfiddle.net/chrisguzman/f7dnfrjf/我已经想出了如何将一个项目附加到每个字典,而不是如何附加其各自的迭代器。

Also, here it is in angular js (bonus points if there is a way to do it with angular): http://codepen.io/chriscruz/pen/GgjGvO?editors=101 此外,这里是角度js(奖励积分,如果有办法角度): http//codepen.io/chriscruz/pen/GgjGvO?edit = 101

Index started from 0, so you need add +1 for each index, like this 索引从0开始,因此您需要为每个索引添加+1 ,如下所示

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

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

Angular demos: 角度演示:

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

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

The runtime system passes 3 parameters to .forEach() : the first is the array element, the second is the index, and the third is the array itself. 运行时系统将3个参数传递给.forEach() :第一个是数组元素,第二个是索引,第三个是数组本身。

Thus: 从而:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM