骚乱将指数推向阵列

时间:2018-01-26 05:49:22

标签: javascript riot.js

我在防暴js中进行了调查,并将以下abclist排序如下。

abclist = [];
abc = {year:year, name1:name1, order:order};
abclist.push(abc);

abclist.sort(function(a,b) {return (a.order > b.order) ? 1 : ((b.order > a.order) ? -1 : 0);} );

在控制台上打印abclist如下所示。

0: {year: "2018", name1: "cc", order: "1"}
1: {year: "2018", name1: "jj", order: "2"}

我想将这些数组索引(0,1)添加到数组中,如下所示。

0: {index:0, year: "2018", name1: "cc", order: "1"}
1: {index:1, year: "2018", name1: "jj", order: "2"}

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

The question is not strictly related to riot.

An easy way to achieve that is to reiterate the array and add a field to each object like this:

for(var i = 0; i < abclist.length; i++){
    abclist[i]['index'] = i; 
}

You can see it in this fiddle: https://jsfiddle.net/7esmssup/6/