0

I've actually a little problem : I want make a function which loop in a object in array.

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){
    for (var i = 0; i < contacts.length; i++) {
        for (var prop1 in contacts[i]) {
            if (contacts[i][prop1] == firstName) {
                if (contacts[i].hasOwnProperty(prop)) {
                    return contacts[i][prop];
                }
            }
         }
     }
 }

 lookUpProfile("Sherlock", "likes");

And I want return two error : "No such contact" and "No such category" (I commentated the part where I placed the "return 'No such contact'" but it's dosen't work...).

2
  • Hi! So just to be sure, you want lookUpProfile to return the first contact that matches? Or, in this particular example, return "No such contact"? Commented Mar 2, 2017 at 21:30
  • "Doesn't work" is not a useful problem description. What's the current issue with your code? Commented Mar 2, 2017 at 21:33

1 Answer 1

1

Try this code:

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) {
  var contact = contacts.find(function(contact) {
    return contact.firstName === firstName;
  });

  if (!contact) {
    return 'No such contact';
  }

  if (!contact.hasOwnProperty(prop)) {
    return 'No such category';
  }

  return contact[prop];
}



console.log(lookUpProfile("Sherlock", "likes"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.