使用jQuery选择JSON值 [英] Selecting json values with jQuery

查看:84
本文介绍了使用jQuery选择JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json对象,如下所示:

I have a json object as follows:

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

我希望获得ID为3的PricePerKilo.

I wish to get the PricePerKilo where the Id is 3.

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

fruits顺便持有json对象...

fruits holds the json object by the way...

我将解释我想在SQL中做些什么,因为我发现用这种方法更容易解释

I will explain what I want to do in SQL, because I find it easier to explain this way

SELECT PricePerKilo From fruits WHERE Id = 3 LIMIT 1

推荐答案

您必须循环! (此外,如果fruits保留JSON而不是数组[不能同时包含两者],则应首先在其上使用jQuery.parseJSON.)

You must loop! (Also, if fruits holds the JSON and not the array [it can’t hold both] then you should use jQuery.parseJSON on it first.)

var i, fruit;

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

fruit将包含Id3undefined的水果(如果不存在).

fruit will contain either the fruit with the Id of 3 or undefined if it didn’t exist.

这篇关于使用jQuery选择JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆