我该怎么办 - JavaScript

时间:2017-03-11 13:15:10

标签: 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");

所以" Kristian"," lastName"应该回归" Vos" " Sherlock","喜欢"应该返回["有趣的案例"," Violin"] 我很困惑这里要做什么 该函数应检查firstName是否为实际联系人的firstName,并且给定属性(prop)是该联系人的属性。

如果两者都为真,则返回"值"该财产。

如果firstName与任何联系人不对应,则返回"没有此类联系人" 我想知道关于如何检查名称是否存在的部分。

2 个答案:

答案 0 :(得分: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"));

答案 1 :(得分:0)

你可以像这样使用lodash,

function lookUpProfile(firstName, prop) {

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

你说你自己会处理'没有这样的联系',你可以通过将查询结果存储在变量中并检查变量来轻松完成。 相信这个answer