gpt4 book ai didi

javascript - 循环并根据 id 将数组放入数组中失败

转载 作者:行者123 更新时间:2023-11-30 12:17:21 25 4
gpt4 key购买 nike

http://jsfiddle.net/rw0z9e2j/

var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];

var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];

var arr = [],
tempObj = {};

$.each(sports, function (i, obj) {
var sport_id = obj.id;

$.each(playersData, function (i, obj) {
if (sport_id == obj.sport_id) {
tempObj = {
"sport_id": obj.sport_id,
"id": obj.id,
"name": obj.name
};
arr.push(tempObj);
}

});
obj.players = arr;
});

console.log(sports);

我尝试建立一个球员数组,并根据 sport_id 将他们放在运动组中,但上述逻辑失败了。 它没有正确分组,sport_id = 1 中的玩家应该去 id = 1 的运动,但为什么没有?

上面的循环有什么问题?

最佳答案

我想这就是你想要的:

var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];

var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];

sports.forEach(function (a) {
var arr = [];
playersData.forEach(function (b) {
if (a.id == b.sport_id) {
arr.push(b);
}
});
a.players = arr;
});

document.write('<pre>' + JSON.stringify(sports, 0, 4) + '</pre>');

关于javascript - 循环并根据 id 将数组放入数组中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091400/

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