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

时间:2015-08-19 09:20:02

标签: javascript jquery loops

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,但为什么没有?

上面的循环有什么问题?

4 个答案:

答案 0 :(得分:2)

我想这就是你想要的:

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>');

答案 1 :(得分:1)

你在你的循环之外声明你的临时vars,这些应该限定在你的循环中并在每次操作后扔掉。

var arr = [],
    tempObj = {};

http://jsfiddle.net/samternent/rw0z9e2j/2/

答案 2 :(得分:0)

你必须把它放在推后:

arr.push(tempObj);
obj.players = arr;

其实你需要这个:

&#13;
&#13;
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 = [];

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

    });
    
});

console.log(sports);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

希望你想进入Sports组,但是你在播放器阵列中加入,请注意,所以请致电

obj.sports = arr;

希望它能解决你的问题。