简体   繁体   English

基于数组的索引将项目添加到对象中的数组

[英]based on index of array add items to array in object

I am scraping a website and have an array of numbers that I am looping over: 我正在抓取一个网站,并且有一系列要遍历的数字:

const arr = [1,2,3,1,2,4,5,6,7];

they correspond to win/lose/draw for different teams: 它们对应于不同团队的赢/输/平局:

ie

1st item in array is won, second is draw, third is loss, fourth is won, fifth is draw, sixth is loss etc. 阵列中的第一个项目获胜,第二个是平局,第三个是损失,第四个是获胜,第五个是平局,第六个是损失等。

How can I loop through these so I have something like the following: 如何遍历这些内容,所以我会看到以下内容:

const teams = [{
  won: 1,
  draw: 2,
  lost: 3
 },{ 
  won: 1,
  draw: 2,
  lost: 4
 },{
  won: 5,
  draw: 6,
  lost: 7
}];

I tried something like the following but it didn't work as I expected. 我尝试了以下类似的操作,但是没有按预期工作。

  const arr = [1, 2, 3, 1, 2, 4, 5, 6, 7]; const newArr = []; arr.forEach((item, index => { if (index % 0 === 0) { newArr.push({ won: item }); } else if (index % 1 === 0) { newArr.push({ draw: item }); } else { newArr.push({ lost: item }); } }); 

Unfortunately, using the array methods like forEach won't work well because you need to consolidate multiple array elements into a single object. 不幸的是,使用像forEach这样的数组方法不能很好地工作,因为您需要将多个数组元素合并到一个对象中。 It's possible, but it would be a bit confusing. 可能,但是会有些混乱。 It might be clearer if you use a for loop: 如果使用for循环,可能会更清楚:

 const arr = [1,2,3,1,2,4,5,6,7]; const teams = []; for (let i = 0; i < arr.length; i += 3) { teams.push({ won: arr[i], draw: arr[i + 1], lost: arr[i + 2], }); } console.log(teams); 

You want 你要

index % 3 === 0; // 0, 3, 6, ...
index % 3 === 1; // 1, 4, 7, ...
index % 3 === 2; // 2, 5, 8, ...

You can loop over your array but only consider every third element by using i+=3 : 您可以遍历数组,但只使用i+=3来考虑每三个元素:

let teams = [];
function teamStats(won, draw, lost){
  return {won, draw, lost};
}
for(let i = 0; i < arr.length; i+=3){
  teams.push(teamStats(arr[i], arr[i+1], arr[i+2]));
}

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

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