David
David

Reputation: 16726

How to find child object with property value using Underscorejs and jQuery?

Take the following data:

object {
   name: 'foo'
   children: [
      {
         'name': 'cat'
         'color': 'green'
      },
      {
         'name': 'dog'
         'color': 'blue'
      },
      {
         'name': 'bird'
         'color': 'red'
      }
   ]
}

How can I use Underscorejs, jQuery and JavaScript to find and select the child where name=dog? I tried using _.findWhere(objectdata.children,{name:'dog'}), but that didn't seem to work either.

Upvotes: 0

Views: 1003

Answers (2)

user7321052
user7321052

Reputation:

With Underscore.js you could simply use a filter function such as:

var child = _.filter(object.children, obj => obj.name === 'dog');

You don't need jQuery for that.

Upvotes: 1

Deep
Deep

Reputation: 9794

In JQuery you can use filter to get the child object.

var obj = {
   name: 'foo',
   children: [
      {
         'name': 'cat',
         'color': 'green'
      },
      {
         'name': 'dog',
         'color': 'blue'
      },
      {
         'name': 'bird',
         'color': 'red'
      }
   ]
};

console.log(obj.children.filter(function(e){return e.name == "dog";})[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions