1.使用for循环的方法处理数据
var list = [{id:7, name:"小一"} ,{id:8, name:"小二"},{id:9, name:"小三"}]
var newList = []
console.log(list);
//结果[{id: 7, name: "小一"},{id: 8, name: "小二"},{id: 9, name: "小三"}]
for (let i = 0; i < list.length; i++) {
const element = list[i];
var object = {
id:element.id,
index: i
}
newList.push(object)
}
console.log(newList);
//结果[{id: 7, index: 0},{id: 8, index: 1},{id: 9, index: 2}]
2.使用forEach的方法
var list = [{id:7, name:"小一"} ,{id:8, name:"小二"},{id:9, name:"小三"}]
var newList = []
list.forEach(function(value,index){
var object = {
id:value.id,
index:index
}
newList.push(object )
})
console.log(newList)
// 结果[{id: 7, index: 0},{id: 8, index: 1},{id: 9, index: 2}]
3.使用map的方法
var list = [
{ id: 7, name: "小一" },
{ id: 8, name: "小二" },
{ id: 9, name: "小三" },
];
var newList = list.map(function (n, i) {
var d = {
id: n.id,
index: i,
};
return d;
});
console.log(newList);
// 结果[{id: 7, index: 0},{id: 8, index: 1},{id: 9, index: 2}]
```