开发者

Comparing JSON value in Jquery

开发者 https://www.devze.com 2023-03-31 06:18 出处:网络
I want to check if \"T1000\" exists as an approval \"key\" in the following JSON. If it exists, then I want to display the corresponding approval \"value\".

I want to check if "T1000" exists as an approval "key" in the following JSON. If it exists, then I want to display the corresponding approval "value".

{"approvals": 
    [
         {"approval":
            {
               "id":"0121920",
               "key":"T100",
               "value":"Ben Tsu"
            }
         },
         {"approval":
            {
               "id":"",
               "key":"T1000",
               "value":"Amy Dong"
            }
         }
    ]
}

I'm getting JSON as an Ajax response. I'm trying to loop through all properties and match it to the value passed in as the parameter.

Here's my code but it only spits out object Object, object Object. So, if I have 5 properties, this code spits out object Object 5 times.

I'm passing inputFieldDefaultValue as a parameter to the plugin with the value being T1000. Hence, o.inputFieldDefaultValue.

$.each(response.approvals, function(index, approvals){ 
    if(approvals.approval.key == o.inputFieldDefaultValue){ 
         approvals.approval.value; 
    } 
}); 

If I do

$.each(response.approvals开发者_Python百科, function(index, approvals){ 
    if(approvals.approval.key == o.inputFieldDefaultValue){ 
         alert(approvals.approval.value); 
    } 
});

it alerts the corresponding value (Amy Dong) but it still writes object Object (as many times as the properties in the JSON response).


You may access the values of the JSON object by using the following code that traverses the objects:

var approvals = obj.approvals;

for(var i = 0; i < approvals.length; i++)
{
  if(approvals[i].approval.key = 'T1000')
  {
    // Display approvals[i].approval.value
  }
}


It can be done without jQuery. You just need Array.prototype.filter and Array.prototype.map:

var aListOfAllValuesFromKeysEqualsToT1000 = json.approvals.filter(function(approval) {
    return approval.key === "T1000";
}).map(function(approval) {
    return approval.value;
});

Then use aListOfAllValuesFromKeysEqualsToT1000 to do whatever you want the values for.


you would first take your json and use JSON.parse(json) to get some object literals. From there you would do

var ary = obj.approvals;
for (var i = 0; i < ary.length; i++) {
  var current = ary[i], val;
  if (current.key === 'T1000') {
    val = current.value;
    break;
  }
}


With jQuery:

var approvals = obj.approvals;
$.each(approvals, function () {
    if (this.approval.key === 'T1000') {
        alert(this.approval.value);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号