0

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.

5
  • Check out this post, you can choose a duplicate for free. Commented Feb 24, 2013 at 21:18
  • check this library jsonselect.org/#overview Commented Feb 24, 2013 at 21:18
  • That doesn't help @Bergi. Commented Feb 24, 2013 at 21:19
  • @OliverJosephAsh: Why not? Convert string in dot notation to get the object reference is exactly what you want. Commented Feb 24, 2013 at 21:21
  • @Bergi It explains how to convert the string into dot notation but that doesn't help me write the filter function. Commented Feb 24, 2013 at 21:23

1 Answer 1

1

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;
    });
});
Sign up to request clarification or add additional context in comments.

6 Comments

This will only work for one property in query: jsbin.com/uqabog/1/edit. Can you think of a solution that will work with multiple properties in query?
I'm a bit confused now (sorry) but I seem to have got it working in ES5 (which is what I started with): jsbin.com/umeros/9/edit. Thanks.
It does for multiple. Only every expects you to return true, otherwise it breaks the loop since it already knows that not every item fulfils the condition.
Yeah, that's the ES5 variant. Only you tagged your question underscore.js, so I used the cross-browser functions (and _.every works directly on objects as well)
What can I do to prevent it erroring when data contains an object that does not match the query? I.e. jsbin.com/umeros/11/edit
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.