我有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" }
]
}
]
我对Underscore.js中的_.where基本了解它会查看列表中的每个值,返回包含属性中列出的所有键值对的所有值的数组。
例如_.where(listOfPlays, {title: "Dollhouse"});
这将返回一个标题为“Dollhouse”的对象,但是如何根据 student 数组的值获得对象?来自listOfPlays
?
我正在寻找类似的东西:
_.where(listOfPlays , {student: [name : "Echo"]});**
答案 0 :(得分:1)
您正在寻找的Copy to another location
方式在新版本中不再有效。
您可以使用:
_.filter查看列表中的每个值,返回通过真值测试(谓词)的所有值的数组
_.some如果列表中的任何值通过谓词真值测试,则返回true。
_.where(listOfPlays , {student: [name : "Echo"]});
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);