我有以下對象數組:返回對象的屬性,一旦發現爲對象的陣列中的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"]
}
];
我想定義一個函數,lookUpProfile(firstName, prop)
,其對輸入數據:
lookUpProfile("Akira", "likes");
將返回:
["Pizza", "Coding", "Brownie Points"]
這是我的解決方案至今沒有返回,直到事現在:
function lookUpProfile(firstName, prop){
for(var i = 0; i < contacts.length; i++){
if(contacts[i].firstName == firstName){
for(var j = 0; j < contacts[i].length; j++){
if(contacts[i].hasOwnProperty(prop))
return prop;
}
}
}
}
有沒有人有任何想法來解決這個問題?謝謝