使用jQuery选择json值

我有一个json对象如下:

[{"Id":"1","Item":"Apples","PricePerKilo":"10.00"}, {"Id":"3","Item":"Oranges","PricePerKilo":"12.00"}] 

我希望得到Id为3的PricePerKilo。

 var fruits = jQuery("#products").data('productData'); 

水果持有json对象的方式……

我将解释我想在SQL中做什么,因为我觉得这样解释起来更容易

 SELECT PricePerKilo From fruits WHERE Id = 3 LIMIT 1 

你必须循环! (另外,如果fruits保存JSON而不是数组[它不能同时保存],那么你应该先使用jQuery.parseJSON 。)

 var i, fruit; for(i = 0; fruit = fruits[i]; i++) { if(fruit.Id == 3) break; } 

fruit不存在, fruit将包含Id3的果实或undefined的果实。

你必须遍历你的数组并选择匹配的id:

 $.each(fruits, function(i, val){ if (val.Id == 3) { // val is now the single fruit object with the id of 3 } });