Sagar Vyas Sagar Vyas - 2 months ago 13
Javascript Question

How to use _.where(list, properties) to get inner array as property?

I have JSON structure as below

var listOfPlays = classRoom: [
{
title: "Dollhouse",
femaleLead: true,
student: [
{ name: "Echo", role: "doll" },
{ name: "Topher", role: "mad scientist" }
]
},
{
title: "Dr. Horrible's Sing-Along Blog",
student: [
{ name: "Billy", role: "mad scientist" },
{ name: "Penny", role: "love interest" }
]
}
]


I know basic about _.where in Underscore.js that it will Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

For example _.where(listOfPlays , {title: "Dollhouse"}); this will return me an object whose title is "Dollhouse", but how would I get an object base on student array's value ? from listOfPlays ?

I am looking something like

_.where(listOfPlays , {student: [name : "Echo"]});

Any input ?

Thanks,
Sagar Vyas

Answer Source

The way _.where(listOfPlays , {student: [name : "Echo"]}); you are looking for does not work anymore in the new version.

You can use:

_.filter that looks through each value in the list, returning an array of all the values that pass a truth test (predicate)

_.some that returns true if any of the values in the list pass the predicate truth test.

var listOfPlays = [{
    title: "Dollhouse",
    femaleLead: true,
    student: [{
        name: "Echo",
        role: "doll"
      },
      {
        name: "Topher",
        role: "mad scientist"
      }
    ]
  },
  {
    title: "Dr. Horrible's Sing-Along Blog",
    student: [{
        name: "Billy",
        role: "mad scientist"
      },
      {
        name: "Penny",
        role: "love interest"
      }
    ]
  }
]

var output = _.filter(listOfPlays, function(item) {
  return _.some(item.student, {
    name: "Echo"
  });
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>