如何使用jQuery each()获取JSON数据中的二级数组值

时间:2014-06-05 14:19:29

标签: javascript jquery json

我想从第二级和第三级数组中使用jquery选择一个特定的值。这是我的JSON响应,如下所示:

{
    "events": [{
        "id": 847843,
        "name": "Strasbourg IG at Limoges CSP",
        "timezone": "GMT",
        "timezoneOffset": 0,
        "time": 1401983400000,
        "timeUtc": "2014-06-05T18:50:00+00:00",
        "status": "live",
        "wpRef": "847843",
        "parentCategoryId": 22,
        "parentCategoryName": "Basketball",
        "categoryId": 7443,
        "categoryName": "French Championnat Pro A ",
        "racingEvent": null,
        "raceNumber": null,
        "marketCount": 3,
        "prefix": null,
        "nameSeparator": null,
        "markets": [{
            "id": 4943131,
            "primitiveType": 2,
            "primitiveName": "Head to Head",
            "typeId": 36,
            "name": "Head to Head",
            "marketDescription": "Select the winner of the match.",
            "marketRules": "Includes extra time.\r",
            "eventNotices": null,
            "autoHide": false,
            "status": "live",
            "bettingStatus": "enabled",
            "period": "Fulltime",
            "allowMultiple": true,
            "betInRunTime": 0,
            "track": null,
            "weather": null,
            "betTypes": [{
                "id": 1,
                "name": "Win",
                "finishingOrder": null,
                "products": []
            }],
            "selections": [{
                "id": 288481048,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Strasbourg IG",
                "prefix": "",
                "mpId": 288481048,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 2.6,
                    "usPrice": "+160",
                    "value": 2.60
                }]
            }, {
                "id": 288481039,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Limoges CSP",
                "prefix": "",
                "mpId": 288481039,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 1.44,
                    "usPrice": "-227",
                    "value": 1.44
                }]
            }]
        }, {
            "id": 4943134,
            "primitiveType": 99,
            "primitiveName": "Other",
            "typeId": 1266,
            "name": "Odd or Even Total",
            "marketDescription": "Select whether the amount of points scored in the match will be an odd or even number (zero = even)\r\rIncludes overtime.",
            "marketRules": "For this market zero will be deemed to be an even number.\r\rNo bonus bets.\r\rIncludes overtime.",
            "eventNotices": null,
            "autoHide": true,
            "status": "live",
            "bettingStatus": "enabled",
            "period": "Fulltime",
            "allowMultiple": true,
            "betInRunTime": 0,
            "track": null,
            "weather": null,
            "betTypes": [{
                "id": 1,
                "name": "Win",
                "finishingOrder": null,
                "products": []
            }],
            "selections": [{
                "id": 288481066,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Even",
                "prefix": "",
                "mpId": 288481066,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 1.85,
                    "usPrice": "-118",
                    "value": 1.85
                }]
            }, {
                "id": 288481075,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Odd",
                "prefix": "",
                "mpId": 288481075,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 1.85,
                    "usPrice": "-118",
                    "value": 1.85
                }]
            }]
        }, {
            "id": 4943137,
            "primitiveType": 99,
            "primitiveName": "Other",
            "typeId": 1298,
            "name": "Match Result",
            "marketDescription": null,
            "marketRules": null,
            "eventNotices": null,
            "autoHide": false,
            "status": "live",
            "bettingStatus": "enabled",
            "period": "Fulltime",
            "allowMultiple": true,
            "betInRunTime": 0,
            "track": null,
            "weather": null,
            "betTypes": [{
                "id": 1,
                "name": "Win",
                "finishingOrder": null,
                "products": []
            }],
            "selections": [{
                "id": 288481102,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Strasbourg IG",
                "prefix": "",
                "mpId": 288481102,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 2.63,
                    "usPrice": "+163",
                    "value": 2.63
                }]
            }, {
                "id": 288481084,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Limoges CSP",
                "prefix": "",
                "mpId": 288481084,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 1.5,
                    "usPrice": "-200",
                    "value": 1.50
                }]
            }, {
                "id": 288481093,
                "betId": null,
                "eventId": null,
                "eventNumber": null,
                "eventName": null,
                "eventTime": null,
                "position": null,
                "name": "Draw",
                "prefix": "",
                "mpId": 288481093,
                "marketPosition": null,
                "marketName": null,
                "marketTypeName": null,
                "marketSelectionId": null,
                "marketSelectionName": null,
                "categoryId": null,
                "categoryName": null,
                "parentCategoryId": null,
                "parentCategoryName": null,
                "maxBet": 0.00,
                "scratched": false,
                "winPrice": null,
                "placePrice": null,
                "finalWinPrice": null,
                "finalPlacePrice": null,
                "finalPrice": null,
                "prices": [{
                    "betTypeId": 1,
                    "betTypeName": "Win",
                    "productId": null,
                    "productName": null,
                    "precisePrice": 13.00,
                    "usPrice": "+1200",
                    "value": 13.00
                }]
            }]
        }],
        "result": null
    }]
}

我可以使用以下代码从事件类别中获取所有“名称”字段。

drawAllEvents: function (events)  {
    var $container = $('#someID ul');
    $.each(events, function(i, event) {
        $('<a />', { text: event.name, href: '#' }).wrap('<li />').parent().appendTo($container);
    });
}

现在我尝试使用另一个函数从markets数组中获取“primitiveName”字段,但由于某种原因它返回undefined。这是我的代码

drawAllBetTypesFilter: function (events)  {
    $('#bettype-sport ul').empty();
    var betTypeFilter = $('#bettype-sport ul');
    $.each(events, function (i, event) {
        $.each(event.markets, function (market) {
            var betTypeName = market.primitiveName;
            $('<a />', {
                text: betTypeName
            }).wrap('<li />').parent().appendTo(betTypeFilter);
        });
    });
}

此外,我如何获取第三级数组,例如,如果我想获取“betTypes”下的所有“name”字段,这是“市场”对象的子项。

编辑:1 - 我的评论中也提到过。如何在列表中将类似的primitiveName值组合在一起,而不是单独显示它们。

这是显示我如何在第一级获取值的小提琴。 FIDDLE LINK

2 个答案:

答案 0 :(得分:2)

传递给each()迭代函数的第一个参数是数组中当前元素的索引,因此在当前代码中,market参数不是数组中的元素,而是int 。试试这个:

var betTypeFilter = $('#bettype-sport ul');
$.each(events, function (i, event) {
    $.each(event.markets, function (i, market) { // <- note 'i' first param
        var betTypeName = market.primitiveName;
        $('<a />', {
            text: betTypeName
        }).wrap('<li />').parent().appendTo(betTypeFilter);

        // to get betTypes for this market:
        $.each(market.betTypes, function(i, betType) {
            // do something...
            console.log(betType);
        });
    });
});

要获取name下的betTypes,需要另外一个循环。或者,如果数组中只有一个对象,则只能对第一个元素进行硬编码访问:

market.betTypes[0].name; // == 'Win'

答案 1 :(得分:0)

或者,不是使用jquery每个函数,为什么不使用传统的javascript循环。 $ .each方法效率不高。

drawAllBetTypesFilter: function (events)  {
    $('#bettype-sport ul').empty();
    var betTypeFilter = $('#bettype-sport ul');
    for(var i = 0; i < events.length; i++) {
        var event = events[i];
        for(var j = 0; j < event.markets.length; j++) {
            var market = event.markets[j];
            var betTypeName = market.primitiveName;
            $('<a />', {
                text: betTypeName
            }).wrap('<li />').parent().appendTo(betTypeFilter);
        };
    };
}