Angela Inniss
Angela Inniss

Reputation: 359

Ternary statement does not return correct data

Hello I am trying to resolve the following:

My function should do the following:

  1. Check if name is an actual contact's firstName and the given property (prop) is a property of that contact.

  2. If both are true, then return the "value" of that property.

  3. If name does not correspond to any contacts then return "No such contact".

  4. If prop does not correspond to any valid properties of a contact found to match name then return "No such property".

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(name, prop){
contacts.forEach((block) => {
    ((name === block.firstName) && (block.hasOwnProperty(prop))) ? block[prop] : "no such property"
   })
return "no such contact"
}

lookUpProfile("Akira", "likes");

I am unsure why it is not working, I have tried to do a ternary statement and use a short circuit operator too.

Thank you in advance

Upvotes: 0

Views: 35

Answers (1)

CptKicks
CptKicks

Reputation: 441

First retrieve the contact using the find method. Then if something is found, you can proceed and check if it has the 'prop' property.

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(name, prop) {
    const found = contacts.find( (block) => {
    return (block.firstName === name)
  });

  if ( found !== undefined ){
    if (found.hasOwnProperty(prop)){
        return found[prop];
    } else {
        return 'No such property'
    }
  } else {
    return 'No such contact';
  }
}

lookUpProfile("Sherlock", "likes");

Upvotes: 1

Related Questions