2017-08-24 88 views
-4

可以說我有一個數組:挑選出在陣列陣列,JSON

[{ 
    "id": 1, 
    "firstName": "Ron", 
    "surname": "Weasley", 
    "friends": [2] 
}, { 
    "id": 2, 
    "firstName": "Harry", 
    "surname": "Potter", 
    "friends": [1, 3] 
}, { 
    "id": 3, 
    "firstName": "hermione", 
    "surname": "granger", 
    "friends": [2, 4] 
}, { 
    "id": 4, 
    "firstName": "Drako", 
    "surname": "Malfoy", 
    "friends": [1, 3] 
}] 

如何過濾它,當我點擊「哈利·波特」,它顯示名稱爲「Drako馬爾福」作爲一個div推薦的朋友(因爲他與哈利有兩個共同的朋友,又因爲德拉科是赫敏和羅恩的朋友)?

+3

能否請你添加你目前的代碼? – Joe

+1

用戶javascript數組排序方法(https://www.w3schools.com/jsref/jsref_sort.asp),這裏有一個版本,您可以傳遞自己的回調函數,因爲您可以比較對象並檢查字段然後根據結果返回-1,1或0。 – SPlatten

+1

你有什麼嘗試?如果德拉科和哈利只有一個共同的朋友呢?如果他們都是朋友呢? – Weedoze

回答

0

使用$ .inArray()方法獲取「firstName」的名字:「Harry」, 「surname」:「Potter」,並使用.each()方法獲取值和檢查值存在於「friends」中: [2],「朋友」:[2,4],「朋友」:[1,3]

0

我假設如果在陌生人和陌生人之間至少有一個共同的朋友,一位推薦的朋友。否則,你應該能夠使用註釋來遵循邏輯。

參考文獻:Array#filterArray#forEach

var data = [{ 
 
    "id": 1, 
 
    "firstName": "Ron", 
 
    "surname": "Weasley", 
 
    "friends": [2] 
 
}, { 
 
    "id": 2, 
 
    "firstName": "Harry", 
 
    "surname": "Potter", 
 
    "friends": [1, 3] 
 
}, { 
 
    "id": 3, 
 
    "firstName": "hermione", 
 
    "surname": "granger", 
 
    "friends": [2, 4] 
 
}, { 
 
    "id": 4, 
 
    "firstName": "Drako", 
 
    "surname": "Malfoy", 
 
    "friends": [1, 3] 
 
}]; 
 

 
function getRecommendedFriend(name) { 
 
    var person = data.filter(function(item) { 
 
    return (item.firstName + " " + item.surname) == name; 
 
    })[0]; 
 
    
 
    var friendsOfPerson = person.friends; 
 
    
 
    var recommendedFriends = data.filter(function(item) { 
 
    // Ignore the person himself. 
 
    if(item.id == person.id) { 
 
     return false; 
 
    } else 
 
    // Ignore the friends of the person. 
 
    if(friendsOfPerson.includes(item.id)) { 
 
     return false; 
 
    } else 
 
    // Return if the person has at least one common friend. 
 
    { 
 
     var friendsOfStranger = item.friends; 
 
     var hasCommonFriend = false; 
 
     
 
     friendsOfStranger.forEach(function(friend) { 
 
     if(friendsOfPerson.includes(friend)){ 
 
      hasCommonFriend = true; 
 
     } 
 
     }); 
 
     
 
     return hasCommonFriend; 
 
    } 
 
    }); 
 
    
 
    return recommendedFriends; 
 
} 
 

 
console.log(getRecommendedFriend("Harry Potter"));