检查对象数组中是否不存在值

时间:2018-01-07 19:50:10

标签: javascript

我必须编写一个函数来检查参数1(firstName)是否是存储在变量(contacts)中的数组oj对象中的值,如果是,则返回当前对象的属性值(prop)。如果firstName不存在,我必须返回“未找到联系人”。如果找不到道具,我必须退回'没有这样的财产'。

我很难弄清楚如何检查在数组对象中是否找不到参数(firstName)。如何编写if语句来检查?

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",
    'youtube': 'nah',
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
  },
  {
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["Javascript", "Gaming", "Foxes"]
  }
];

function lookUpProfile(firstName, prop){

  for (i=0;i<contacts.length;i++) {
    if (Object.values(contacts[i]).indexOf(firstName) > -1 && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
  }
    if (!contacts[i].hasOwnProperty(prop)) {
      return 'No such property';
    }
  } 
}

lookUpProfile("Sherlock", "likes");

5 个答案:

答案 0 :(得分:2)

您使用Array.find查找具有正确firstName的对象。您可以按如下方式使用它:

function lookUpProfile(firstName, prop) {
    var profile = contacts.find(function(contact) {
        return contact.firstName === firstName;
    });

    if (!profile) {
        console.log("no profile found for " + firstName);
        return;
    }

    if (!profile[prop]) {
        console.log("no " + prop + " found on " + firstName + " profile");
        return;
    }

    return profile[prop];
}

答案 1 :(得分:1)

&#13;
&#13;
<html>

<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <div id="wrapper">
    <div id="headerwrap">
      <div id="header">
      </div>
    </div>
    <div id="navigationwrap">
      <div id="navigation">
        <ul>
          <li><a href="">main menu</a></li>
          <li><a>test</a>
            <ul class="sub-menu">
              <li><a href="">test1</a></li>
              <li><a href="">test2</a></li>
              <li><a href="">test3</a></li>
              <li><a href="">test4</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
    <div id="navigationwrap_placeholder"></div>
    <div id="leftcolumnwrap">
      <div id="leftcolumn">
        <p></p>
      </div>
    </div>
    <div id="contentwrap">
      <div id="content">
        <br>
        <br>
        <p>Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices.
          Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci
          luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. </p>
        <br>
        <br>
      </div>
    </div>
    <div id="rightcolumnwrap">
      <div id="rightcolumn">
        <p></p>
      </div>
    </div>
    <div id="footerwrap">
      <div id="footer">
      </div>
    </div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
var check = (first, prop) => (obj.map(cur => cur.firstName === first ? cur.firstName : "Not found")[0]);

var obj = [{
 firstName: "Eduardo",
 age: 17
}];

console.log(check(obj[0].firstName));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您当前的方法不允许区分这两个错误情况,因为您尝试将两个条件(名称和属性)组合在循环体内的单个if条件中。

此外,您的方法不允许lookUpProfile函数的用户区分真实错误和道具存在且具有值'No contact found''No such property'的特殊情况。你可能最好不要抛出异常而不是返回错误字符串。

一种工作方法是首先过滤具有匹配名称的候选人,然后找到具有所需属性的第一个候选人:

function lookUpProfile(firstName, prop) {
  const candidates = contacts.filter(contact => contact.firstName === firstName);
  if (candidates.length === 0) throw new Error('No contact found');
  const match = candidates.find(candidate => candidate.hasOwnProperty(prop));
  if (!match) throw new Error('No such property');
  return match[prop];
}

答案 4 :(得分:0)

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",
    'youtube': 'nah',
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
  },
  {
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["Javascript", "Gaming", "Foxes"]
  }
];

function lookUpProfile(firstName, prop){

  for (i=0;i<contacts.length;i++) {
    if (Object.values(contacts[i]).indexOf(firstName) > -1 && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
  }
    if (!contacts[i].hasOwnProperty(prop)) {
      return 'No such property';
    }
  } 
}

lookUpProfile("Sherlock", "likes");