Check if a object is defined, best practice.

前端 未结 4 774
滥情空心
滥情空心 2020-12-15 17:04

I have the following JSON response from a ajax-request.

var json = {
    \"response\": {
        \"freeOfChargeProduct\": {  
        \"description\": \"Prod         


        
4条回答
  •  -上瘾入骨i
    2020-12-15 18:00

    You could do something like this:

    try{
        var focp = json.response.freeOfChargeProduct
        var text = "You get " + focp.qty + " of " +
            focp.productName +
            " for only $" + (focp.qty-focp.details.focQuantity)*focp.details.price +
            ", You save $" + focp.details.focQuantity*focp.details.price;
        $("order_info").innerText = text;
    } catch(e) {
        // woops, handle error...
    }
    

    It would generate a message like this from the provided data in your question if the fields exists:

    You get 6 of XYZ for only $277,5, You save $55.5

    If the data is non-existing, you'll end up in the catch block. You could always just to a Try, Catch, Forget here if you can't come up with a way to handle the error (Maybe do a new AJAX request for the data?).

提交回复
热议问题