如何使用 _.where(list, properties) 获取内部数组作为属性?



我有如下JSON结构

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" }
]
}
]

我对下划线中的 _.where 有基本的了解.js它将查看列表中的每个值,返回包含属性中列出的所有键值对的所有值的数组。

例如_.where(listOfPlays, {title: "Dollhouse"});这将返回一个标题为"娃娃屋"的对象,但是我如何根据学生数组的值获得一个对象? 从listOfPlays

?我正在寻找类似的东西:

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

您正在寻找_.where(listOfPlays , {student: [name : "Echo"]});的方式在新版本中不再有效。

您可以使用:

_.filter,用于查看列表中的每个值,返回通过真值检验(谓词)的所有值的数组

_.some,如果列表中的任何值通过谓词真值检验,则返回 true。

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>

最新更新