0

I have a json object returned from my c# code. I am looping through the result in jquery.

everything is working fine BUT this is just a sample object. actual object is way much bigger and the current method which i am using is not very clean. could any one help me how do i loop through object inside object.

Here is my code..

Response JSON

[
   {
      "ProductId":7363,
      "ProductName":"Brisk Waterproof Men\u0027s Jacket",
      "ProductDetails":{
         "ImagePath":"/assets/productimages/017/017271_BLA_MENS_BRISK_JACKET_-(10).jpg",
         "ImageAltText":"BLACK:3",
         "ProductSummary":"Waterproof & taped seams\r\nHighly breathable fabric\r\nDouble storm flap\r\nMultiple pockets",
         "MSRP":{
            100.00      
         },
         "Price":{
           65.00
         }
      },
      "StatusCode":"Success",
      "ErrorMessage":null
   },
   {
      "ProductId":6941,
      "ProductName":"Fizz Kid\u0027s Waterproof Jacket",
      "ProductDetails":{
         "ImagePath":"/assets/productimages/016/016792_BLA_FIZZ_KIDS_JACKET_SS13_4.jpg",
         "ImageAltText":"BLACK:5",
         "ProductSummary":"Waterproof & taped seams\r\nDetachable hood\r\nAdjustable hem\r\nMultiple pockets",
         "MSRP":{
              150.00
         },
         "Price":{
             129.00
         }
      },
      "StatusCode":"Success",
      "ErrorMessage":null
   }
]

jQuery

$('.btnGo').on("click", function (e) {
    console.log("click event fired");
    var jsonData = [{
        ProductId: "7363"
    }, {
        ProductId: "6941"
    }];
    $.ajax({
        url: "/JsonHelper/ProductHelper.ashx",
        data: JSON.stringify(jsonData),
        dataType: 'json',
        type: 'POST',
        contentType: 'application/json',
        success: function (data) {
            $.each(data, function (key, value) {
                console.log('Object: ' + key);
                var details = value.ProductDetails;
                var MSRP = value.ProductDetails.MSRP;
                var price = value.ProductDetails.Price;
                console.log(details);
                console.log(MSRP);
                console.log(price);
                $('.resultJson').append("<br />");
                $.each(value, function (k, v) {
                    $('.resultJson').append(k + ":    " + v + "<br />");
                    if (k == "ProductDetails") {
                        if (details != null) {
                            $.each(details, function (dk, dv) {
                                $('.resultJson').append(dk + ":    " + dv + "<br />");
                            });
                        }
                    }
                    if (k == "MSRP") {
                        if (MSRP != null) {
                            $.each(MSRP, function (mk, mv) {
                                $('.resultJson').append(mk + ":    " + mv + "<br />");
                            });
                        }
                    }
                    if (k == "Price") {
                        if (price != null) {
                            $.each(price, function (pk, pv) {
                                $('.resultJson').append(pk + ":    " + pv + "<br />");
                            });
                        }
                    }
                });
                $('.resultJson').append("----------------  ------------------");
            });
        },
        error: function (data, status) {
            console.log("FAILED:" + status);
        }
    });
});

I am very confused about $.each and dont know how to efficiently loop through mulitple objects.

8
  • 1
    Have you looked into using for loops instead of each? It could help you here. w3schools.com/js/js_loop_for.asp Commented Aug 27, 2013 at 12:12
  • you are doing it right, what else do you need? Commented Aug 27, 2013 at 12:12
  • If you hope to get any answer, you should only show the relevant code instead if just giving your whole jquery event handling ;) Commented Aug 27, 2013 at 12:12
  • 1
    You should be able to just use the objects directly, and not loop at all, except that you need one outer loop because you start with an array. Commented Aug 27, 2013 at 12:24
  • 1
    You also need to fix this: "MSRP": {100.00}. Presumably it should be just MSRP: 100.00, and similarly for Price. But if it's an object, then you need, say, "MSRP": {"val": 100.00}. Or if this happens to be the only value in what could be a multiple-valued array, you might want "MSRP": [100.00]. Commented Aug 27, 2013 at 12:27

1 Answer 1

1

I'd suggest that if your data is consistent, then you're better off working directly with the format and not looping through everything to find keys and values. I created a Fiddle using your code (skipping the AJAX part.) and for contrast another Fiddle with the following code:

var success = function (data) {
    var product, i, len, $output = $('.resultJson');
    for (i = 0, len = data.length; i < len; i++) {
        product = data[i];
        console.log('Object: ' + i);
        var details = product.ProductDetails;
        var MSRP = product.ProductDetails.MSRP;
        var price = product.ProductDetails.Price;
        console.log(details);
        console.log(MSRP);
        console.log(price);

        $output.append("<br />");
        $output.append("ProductId: " + product.ProductId + "<br />");        
        $output.append("ProductName: " + product.ProductName + "<br />");        
        $output.append("ProductDetails: " + "<br />");
        if (details) {
            $output.append("ImagePath: " + details.ImagePath + "<br />");
            $output.append("ImageAltText: " + details.ImageAltText + "<br />");
            $output.append("ProductSummary: " + details.ProductSummary + "<br />");
            $output.append("MSRP: " + MSRP + "<br />");
            $output.append("Price: " + price + "<br />");
        }
        $output.append("StatusCode: " + product.StatusCode + "<br />");        
        $output.append("ErrorMessage: " + product.ErrorMessage + "<br />");        
        $('.resultJson').append("----------------  ------------------");
    }
};

I think the latter is much easier to understand. Of course all this is moot if your data is less consistent.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 and accepted your answer for the working Fiddle. My code was also working BUT i was looking for a cleaner solution which you provided..

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.