重构查找函数

Refactoring Lookup Function

我正在尝试重构此功能,但遇到了困难。该函数试图完成的是查找 JSON 对象中是否存在联系人,如果存在,则确定提供的第二个参数是否是指定对象上存在的 属性。

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){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
   if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
   }

}

  for (var j = 0; j < contacts.length; j++) {
   if (contacts[j].firstName !== firstName) {
      return "No such contact";
   } else if (!contacts[j].hasOwnProperty(!prop)) {
      return "No such property" ; 
   }

}

// Only change code above this line
}

// Change these values to test your function
lookUpProfile("kyle", "lastName");

我不太确定你想做什么。该函数可以报告这两种情况的唯一方法是让它 return 一个包含结果的对象。 试试这个。

function lookUpProfile(firstName, prop){
// Only change code below this line
    var result ={contactExist: false, secondParameter:false};
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === firstName) {
            result.contactExists=true;
           result.secondParameter= contacts[i][prop]!=null;
            return result;
        }
    }
    return result;

// Only change code above this line
}

无需像您当前那样循环两次该函数。快速更改会给你这样的东西:

function lookUpProfile(firstName, prop){
    var nameFound = false;

    for (var i = 0; i < contacts.length; i++) {
        var contact = contacts[i];
        // if a correct name is found, store that
        if(contact.firstName === firstName){
            nameFound = true;
            if(contact.hasOwnProperty(prop)) {
                return contact[prop];
            }
        }                
    }

    return nameFound ? "No such property" : "No such contact";
}

基本上,您只需要在找到特定名称的过程中添加一个检查。如果 属性 存在,该函数将 return 对象,但如果恰好到达末尾(未找到匹配项),您知道是否找到了名称。

假设您只想return找到的第一个匹配项。

filter 排除任何匹配项,return true 如果 属性 找到 else false

function lookUpProfile(firstName, prop) {
  var list = contacts.filter(function (el) {
    return el.firstName === firstName;
  });
  return list.length && list[0][prop] ? true : false;
}

lookUpProfile("kyle", "lastName"); // false
lookUpProfile("Akira", "lastName"); // true
lookUpProfile("Akira", "password"); // false

DEMO