4

I would like to select a particular value using jquery each from the second and third level array. This is my JSON response looks like:

{
    "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
    }]
}

I am able to fetch all the "name" field from events category using the below code.

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

Now I am trying to fetch "primitiveName" field from the markets array using another function but for some reason it returns undefined. Here is my code

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

Furthermore, How do I fetch third level array, for e.g If I want to fetch all "name" fields under "betTypes" which is a child of "markets" object.

EDIT: 1 - Also mentioned in my comment. How do I group similar primitiveName values together in my list instead of displaying them seperately.

Here is the fiddle to show how am I fetching values in first level. FIDDLE LINK

2 Answers 2

3

The first parameter passed to the each() iteration function is the index of the current element in the array, so in your current code your market parameter is not the element from the array but instead an int. Try this:

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

To fetch the name under betTypes would take another loop. Or, if there is only ever one object in the array you could hard-code access to the first element only:

market.betTypes[0].name; // == 'Win'
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Yes I missed looping the index, it works now. Could you please 2 more doubts. 1) As you can see in the JSON, there are 2 similar primitiveName returned from the JSON response. How do I group them together and instead of displaying them seperately in a list I would prefer to show something like "Other (2)" Second question: if there are more objects in the third level array the each loop would look like $.each(event.markets.betTypes, function (i, betTypes) ??
1) I'm not sure what you mean? I guess you're after some kind of expanding element that shows more detail on click? If so, I'd start a new question for that. 2) No, it would need to be tied to a specific market, so inside the each() for event.markets: $.each(market.betTypes, function(i, betType). I added an example to my answer.
I am not looking for addition details on click event. As you can see in this fiddle (jsfiddle.net/7EYUB/3) I am displaying "other" twice since I have same parameter name in the JSON. I would like to group them together, so instead of printing "other" twice I would simply display like "other (2)"
0

Alternatively, instead of using the jquery each function, why not just use traditional javascript looping. The $.each method isn't nearly as efficient as that.

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

5 Comments

Thanks. Can you shed some light on the comment I posted above and the edit I made in my question.
If you are looking to group items with a similar primitive name you need a function that can determine what the group. For example, are you going merge bet types, selections, prices so that all the content from each record are stored together? I did something similar with grades for a school district. For them, I found once I had displayed the class once, ignore the rest. I used a dictionary to check to see if I had visited a class or not.
In another part of the application, they wanted to merge an array of attendance items based on the class. In the end, I looped through the data first to structure the data into something meaningful for the interface.
Yes I am looking something like that. But instead of ignoring the rest as you mentioned in your comment I want to display them as a group. So for e.g. If I have 3 similar names in the JSON (lets say 'ABC') I would like to display them as ABC (3)
Ok, so what you can do is create a new javascript object array and do the calculation. Everytime you find a matching name you could do one of two things. When creating each new object it could have either a sub array of the items found, so you would then need to get the length of that array which would return 3 and preserve the content for access. Alternatively, you could just add a counter property that counts everytime that name is found and increments on the new object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.