rept
rept

Reputation: 2236

Doing a jQuery.grep on a json with children

I have a json string containing products with under those products, sizes, types, prices, ...

One looks like this:

"products": [
    {
        "id": 10,
        "product_prices": [
            {
                "product_size_id": 2,
                "price": "2.0"
            },
            {
                "product_size_id": 3,
                "price": "3.0"
            },
            {
                "product_size_id": 5,
                "price": "4.0"
            },
            {
                "product_size_id": 6,
                "price": "5.0"
            }
        ]

Now I found this post to query and the fiddle is working: How to filter a Multi-dimension JSON object with jQuery.grep()

However when I try to do that it is returning all the object instead of just the product with id=20

This is the code I'm using:

json.data = jQuery.grep(json.products,function(element, index){ return element.id=20})

console.log(json.data);

This is my first json experience to bear with me :-)

I created a fiddle for it:

http://jsfiddle.net/rept/TC25X/

Thanks!

Upvotes: 0

Views: 2597

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219936

Use == for comparing values:

json.data = jQuery.grep(json.products, function (element, index) {
    return element.id == 20;
});

Here's your fiddle: http://jsfiddle.net/TC25X/1/

Upvotes: 2

Related Questions