gpt4 book ai didi

javascript - 如何将数据从一个数组/对象推送到另一个数组/对象中?

转载 作者:行者123 更新时间:2023-12-01 00:03:42 25 4
gpt4 key购买 nike

我正在构建的应用程序使用 XMLHttpRequest,并且我已将响应文本解析为一个名为 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 not a function”。

我已将对象从常规对象更改为数组,push 函数现在不应该工作吗?我这里哪里出错了?我已经被困在这个问题上有一段时间了,非常感谢任何帮助!

谢谢!克里斯

最佳答案

有更好的方法可以做到这一点,但让我们从解决问题开始。

错误显示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]);
}

关于javascript - 如何将数据从一个数组/对象推送到另一个数组/对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60537538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com