Lev Kozak
Lev Kozak

Reputation: 23

lodash _.filter return empty array

I'm stuck in Angular.js using lodash _.filter.

$scope.test = [
    { name: 'FirstName', items: ["Phone", "Tablet"] },
    { name: 'FirstName', items: ["TV"] },
];
$scope.items = [
    { item: "Phone" },
    { item: "Tablet" }
]
$scope.fined = [];
$scope.fined = _.filter(test, _.matches(items));
console.log(fined)// result []

I Expected:

$scope.fined= [{name:'FirstName',items:["Phone","Tablet"]}];

I don't know why but _.filter return empty array :-(

Some ideas?

Upvotes: 1

Views: 2726

Answers (1)

m90
m90

Reputation: 11812

_.matches works in a way that you pass an object whose key value pairs are then being checked in the returned predicate function. So your case should look like this:

var test = [
    { name: 'FirstName', items: ["Phone", "Tablet"] },
    { name: 'FirstName', items: ["TV"] },
];
var items = { items:  ["Phone", "Tablet"] };

var fined = _.filter(test, _.matches(items));
console.log(fined);

Quoting the docs:

This method supports comparing arrays, booleans, Date objects, numbers, Object objects, regexes, and strings. Objects are compared by their own, not inherited, enumerable properties.

Note that this will not work when using underscore as this will not do the deep checking on the Array elements.

See a working example

Upvotes: 1

Related Questions