2017-03-11 193 views
-2

我參加過一門課程,並且在這裏有一個項目。我應該在這裏做什麼 - JavaScript

var contacts = [ 
{ 
    "firstName": "Akira", 
    "lastName": "Laine", 
    "number": "0543236543", 
    "likes": ["Pizza", "Coding", "Brownie Points"] 
}, 
{ 
    "firstName": "Harry", 
    "lastName": "Potter", 
    "number": "0994372684", 
    "likes": ["Hogwarts", "Magic", "Hagrid"] 
}, 
{ 
    "firstName": "Sherlock", 
    "lastName": "Holmes", 
    "number": "0487345643", 
    "likes": ["Intriguing Cases", "Violin"] 
}, 
{ 
    "firstName": "Kristian", 
    "lastName": "Vos", 
    "number": "unknown", 
    "likes": ["Javascript", "Gaming", "Foxes"] 
    } 
    ]; 


    function lookUpProfile(firstName, prop){ 

    } 

    // Change these values to test your function 
    lookUpProfile("Akira", "likes"); 

因此,「克里斯蒂安」,「姓氏」應該返回「沃斯」 和「福爾摩斯」,「喜歡」應該返回[「有趣案例」,「小提琴」] 我很困惑在這裏做什麼 該函數應檢查firstName是否爲實際聯繫人的firstName,並且給定屬性(prop)是該聯繫人的屬性。

如果兩者均爲真,則返回該屬性的「值」。

如果firstName不對應任何聯繫人,則返回「沒有這樣的聯繫人」 我想知道如何檢查名稱是否存在的部分。

回答

1

您可以使用Array.prototype.find()。請注意,它只會返回第一場比賽 - 所以,如果你有相同的名稱(在你的例子沒有給出)多的人,你必須切換到filter()

var contacts = [{ 
 
    "firstName": "Akira", 
 
    "lastName": "Laine", 
 
    "number": "0543236543", 
 
    "likes": ["Pizza", "Coding", "Brownie Points"] 
 
    }, 
 
    { 
 
    "firstName": "Harry", 
 
    "lastName": "Potter", 
 
    "number": "0994372684", 
 
    "likes": ["Hogwarts", "Magic", "Hagrid"] 
 
    }, 
 
    { 
 
    "firstName": "Sherlock", 
 
    "lastName": "Holmes", 
 
    "number": "0487345643", 
 
    "likes": ["Intriguing Cases", "Violin"] 
 
    }, 
 
    { 
 
    "firstName": "Kristian", 
 
    "lastName": "Vos", 
 
    "number": "unknown", 
 
    "likes": ["Javascript", "Gaming", "Foxes"] 
 
    } 
 
]; 
 

 

 
function lookUpProfile(firstName, prop) { 
 
    let profile = contacts.find(contact => contact.firstName === firstName); 
 
    if (!profile) return "No such contact"; 
 
    return profile[prop] || "No such property"; 
 
} 
 

 
// Change these values to test your function 
 
console.log(lookUpProfile("Akira", "likes"));

0

你可以使用lodash像這樣,

function lookUpProfile(firstName, prop) { 

    return _(contacts) 
    .filter(c => c.firstName === firstName) 
    .map(prop) 
    .value(); 
} 

你說你會處理「沒有這樣的接觸」你自己,你可以很容易地通過存儲在變量中查詢的結果和檢查變量做。 貸:此answer