for循环后排序返回

时间:2020-04-29 12:21:33

标签: javascript arrays

我从API获取数据,然后运行它进行循环以获取数组中的所有对象。我将所需的数据保存为const值。

getmatchdata()的输出看起来像这样

["kINGPINj", 17, 13, 4],["AtZe", 15, 22, 5],["AtZe", 20, 21, 8],["Vetements", 25, 26, 10]...

但是,我确实希望将getmatchdata()中的数据放入一个大数组中,然后将其过滤到每个用户名中。 关于如何实现此目标的任何想法,是否应该使用for循环以外的其他方法?

const matchlistResponse = await fetch(`https://api.site.com/match/get?_=&id=${id}`);
const matchlistResponsestats = await matchlistResponse.json();
let matchArray = matchlistResponsestats.players.length
async function getmatchdata() {

  for (var i = 0; i < matchArray; i++) {
    if(matchlistResponsestats.players[i].username === username) {
      const username = matchlistResponsestats.players[i].username
      const kills = matchlistResponsestats.players[i].kills
      const deaths = matchlistResponsestats.players[i].deaths
      const headshots = matchlistResponsestats.players[i].headshots
      return [username, kills, deaths, headshots]
    }
  }
}
let playerstats = await getmatchdata()
console.log(playerstats)

编辑:

我希望输出像这样

[
  {
    "kINGPINj": [
      {
        "id": 0,
        "kills": 17,
        "deaths": 13,
        "headshots": 4
      }
    ]
  },
  {
    "AtZe": [
      {
        "id": 0,
        "kills": 15,
        "deaths": 22,
        "headshots": 5
      },
      {
        "id": 1,
        "kills": 20,
        "deaths": 21,
        "headshots": 8
      }
    ]
  }

]

2 个答案:

答案 0 :(得分:0)

filtermap在这里很适合。

连锁方式:

matchlistResponsestats.filter((item) => item.username === 
username)
.map((item) => {
    return {
      item.name: [{id: item.id, kills: item.kills, deaths: item.deaths, 
      headshots: item.headshots}]
   }
})

说明

1)filter将返回匹配条件的数组(item.username === 用户名)到地图功能

2)map将获得过滤后的数组,并以所需格式返回对象数组

常规方式:

let filteredArray = matchlistResponsestats.filter((item) => item.username === 
    username)

let desiredArray = filteredArray.map((item) => {
        return {
          item.name: [{id: item.id, kills: item.kills, deaths: item.deaths, 
          headshots: item.headshots}]
       }
    })

答案 1 :(得分:0)

let input = [["kINGPINj", 17, 13, 4],["AtZe", 15, 22, 5],["AtZe", 20, 21, 8],["Vetements", 25, 26, 10]];

function storeByKey(input) {
  let map = {};
  for (let e of input)
  {
      if (map[e[0]] == undefined)
      {
          map[e[0]] = [[e[1], e[2], e[3]]];
      } else {
          map[e[0]].push([e[1], e[2], e[3]]);
      }
  }
  return map;
}

console.log(storeByKey(input));