Selecting json values with jQuery

前端 未结 2 852
南笙
南笙 2021-01-27 08:27

I have a json object as follows:

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


        
相关标签:
2条回答
  • 2021-01-27 08:47

    You would have to loop through your array and select the id that matches:

    $.each(fruits, function(i, val){
        if (val.Id == 3) {
            // val is now the single fruit object with the id of 3
        }
    });
    
    0 讨论(0)
  • 2021-01-27 09:03

    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 will contain either the fruit with the Id of 3 or undefined if it didn’t exist.

    0 讨论(0)
提交回复
热议问题