如何将数据从数组/对象推入另一个数组/对象?

时间:2020-03-05 02:50:56

标签: javascript arrays

我正在构建的应用程序使用XMLHttpRequest,并且已将responsetext解析为一个名为data3的变量,该变量返回以下内容:

[]
0: {round_fk: "1", player_name: "John Doe", player_score: "-45"}
1: {round_fk: "1", player_name: "Mark Doe", player_score: "-7"}
2: {round_fk: "2", player_name: "Dave Doe", player_score: "-7"}
3: {round_fk: "2", player_name: "Chris Doe", player_score: "-7"}

我正在尝试根据round_fk对对象数组进行排序,并将具有相同round_fk的所有回合放入另一个数组,其中每个对象都有一个与round_fk对应的键。看起来像这样:

let sortRounds = [
    [
      1: round_fk: "1", player_name: "John Doe", player_score: "-45",
         round_fk: "1", player_name: "Mark Doe", player_score: "-7"
    ],
    [
      2: round_fk: "2", player_name: "Dave Doe", player_score: "-7",
         round_fk: "2", player_name: "Chris Doe", player_score: "-7"
    ]
];

到目前为止,这就是我所拥有的:

let sortRound = [];
          console.log(sortRound);
          for(i = 0; i < data3.length; i++){
            let roundFk = data3[i].round_fk;
            if(!(roundFk in sortRound)){
              sortRound[roundFk] = [];
            }
            Object.keys(sortRound).forEach(function(key){
              if(key == roundFk){
                key.push(data3[i]);
              }
            });
          }

我用对应于round_fk的键创建了一个数组,但是当我尝试将数据推入这些新键时,出现以下错误消息“ Uncaught TypeError:key.push is a function”。

我已将对象从常规对象更改为数组,push函数现在不应该工作吗?我在哪里错了?我已经为此停留了一段时间,非常感谢您的帮助!

谢谢! 克里斯

1 个答案:

答案 0 :(得分:2)

有更好的方法可以解决此问题,但让我们首先解决问题。

错误显示Uncaught TypeError: key.push is not a function。这是指这一行:

key.push(data3[i]);

应该是

sortedRounds[key].push(data3[i]);

为什么?

您正在尝试.push输入密钥。在数组(例如sortRounds)中,键看起来像[0,1,2]

因此您的代码等效于0.push(data3[i])。您不能推到0!它不是数组。

更好的解决方案

let sortRound = [];
for(i = 0; i < data3.length; i++){
  let roundFk = data3[i].round_fk;
  if(!(roundFk in sortRound)){
    sortRound[roundFk] = [];
  }

  // We already know the correct key here, 
  // so no need to loop through the array again
  sortRound[roundFk].push(data3[i]);
}