Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested jQuery.grep

Tags:

arrays

jquery

We can use $.grep to filter out unwanted array items, so

data = $.grep(jsonstr, function(d) {
    return d.attr == "x";
})

will return only those array objects with attr == x

What if I want to similarly filter arrays that sit under objects, can I do that with $.grep? So

    data = $.grep(jsonstr2, function(d) {
        $.grep(d.GL2_ACCTS, function(gl2) {
            return (gl2.localamt > lBound && gl2.localamt < uBound);
        });
        return d.DOC_TYPE == doc;
    }); 

should that filter the arrElement arrays that sit within each element in data?

Data looks as follows:

jsonstr =  
[{
  DOC_TYPE: "1A", 
  GL1_ACCOUNT: "Other|Mark Up(Other)", 
  GL2_ACCTS: [
    {name: "Expenses|Conferences(Expenses)", localamt: 123, count: 2},
    {name: "Expenses|Consultancy(Expenses)", localamt: 49, count: 1}
  ]
}]

I'm calling this as I change lBound and uBound. It only ever returns everything, no filtering happens.

like image 795
hwilson1 Avatar asked Apr 28 '26 20:04

hwilson1


1 Answers

You need to store the filtered array back in the object.

data = $.grep(jsonstr2, function(d) {
    d.GL2_ACCTS = $.grep(d.GL2_ACCTS, function(gl2) {
        return (gl2.localamt > lBound && gl2.localamt < uBound);
    });
    return d.DOC_TYPE == doc;
});

Note that this will filter out the accounts even in objects that weren't returned by the outer $.grep. If you don't want to do that, you need to do the DOC_TYPE check first:

data = $.grep(jsonstr2, function(d) {
    if (d.DOC_TYPE == doc) {
        d.GL2_ACCTS = $.grep(d.GL2_ACCTS, function(gl2) {
            return (gl2.localamt > lBound && gl2.localamt < uBound);
        });
        return true;
    } else {
        return false;
    }
});
like image 196
Barmar Avatar answered Apr 30 '26 10:04

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!