0

I have a json object as follows:

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

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

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

fruits holds the json object by the way...

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I like this approach, but wouldn't fruit hold the last fruit object if the id didn't exist?
@Steve: It’s an unusual loop :) Instead of i < fruits.length, the condition is fruit = fruits[i]. So it exits when fruit becomes undefined.
Ah... good call. But wouldn't that give you a JS error when trying to access Id of undefined? Shouldn't it be if (fruit && fruit.Id ==3)?
@Steve: No, the loop will break before that happens. It’s like while(fruit = fruits[i]) { … }.
Aaah... I think I get it now. The json provided in the question is a json object containing an array. The array index for Apples is 0 and array index for Oranges is 1. Each array index holds name/value pairs. I have to loop through the index to find my required name/value pair?
|
0

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
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.