0

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!

Community
  • 1
  • 1
rept
  • 2,086
  • 1
  • 26
  • 44

1 Answers1

2

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/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292