user1082754
user1082754

Reputation:

Filtering a object with query that contains reference to nested object

I need to write a filter function that will allow me to query by nested object, like this:

var data = [
             { twitter: { id: 1, name: "Bob" } },
             { twitter: { id: 2, name: "Jones" } }
           ],
    query = { 'twitter.id': 1 };

# Perform filter using data and query variables
var search = …

console.log(search);
> ["0"]

The filter should return an array of indexes that match the query.

I currently have this working without nested object support at http://jsbin.com/umeros/2/edit.

However, I would like to be able to query for nested objects, such as the query seen above.

Upvotes: 0

Views: 3034

Answers (1)

Bergi
Bergi

Reputation: 664464

Using the function ref from this answer, your filter should look like this:

var search = _.filter(_.keys(data), function (key) {
    var obj = data[key];
    return _.every(query, function (val, queryKey) {
        return ref(obj, queryKey) === val;
    });
});

Upvotes: 1

Related Questions