Snabow
Snabow

Reputation: 331

underscore.js : _.where() work with first argument but not the second

I'm a beginner in underscore.js, I'm trying to use _.where() to filter my data, with two parameters.

My json data.foo looks like this :

{"foo":[
    {"vag_id":"6","ind_id":"ade","res":"76.56","tx":"66"},
    {"vag_id":"6","ind_id":"aha","res":null,"tx":null}
...
]}

And my code like this :

ind_id = $('#fk_ind_id').val(); // return 'ade'
vag_id = $('#fk_vag_id').val(); // return 6
data_res = _.where(data.foo, { vag_id : vag_id , ind_id : ind_id });

and when I trying to do console.log(data_res), it equal to [] ... When I'm use _.where() with only vag_id parameter, it work fine.

Don't see where is the problem ...

Upvotes: 0

Views: 128

Answers (2)

Thiago Negri
Thiago Negri

Reputation: 5351

This works fine:

var data = {
    foo: [
        {"vag_id":"6","ind_id":"ade","res":"76.56","tx":"66"},
        {"vag_id":"6","ind_id":"aha","res":null,"tx":null}
    ]
};

var data_res = _.where(data.foo, { vag_id : '6' , ind_id : 'ade' });

console.log(JSON.stringify(data_res));

If you look at UnderscoreJS annotated source, you see that _.where uses _.matches which issues strict equality checks (===). Your problem may be a mismatched type, e.g. comparing 6 (number) with "6" (string).

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47172

Your vag_id from the DOM Node is a number. Changing it to a string as your data is will make it work.

Underscore's where() offloads into filter() and matches() which is why types matter.

Upvotes: 1

Related Questions