0

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.

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.