2017-08-28 63 views
0

我JSON結構如下圖如何使用_.where(list,properties)將內部數組作爲屬性?

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」的對象,但我如何獲得一個基於的學生數組的值?從listOfPlays

我要尋找類似:

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

'[名: 「回聲」]'是不是JS有效。你是不是指'[{name:「Echo」}]'? (它仍然不起作用,AFAIK,但它至少不是語法錯誤。) – Amadan

回答

1

_.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>

相關問題