-2

How do you access properties of a javascript object like the following? Please explain each step if possible.

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 lookUp(firstName, prop){

     //code here

 }

I would like to be able to access the name of a contact. So for example

                      lookUp("Akira", "likes") 

should give me the name and the likes. And also lookUp("Drew", "like") should give me back "No such contact".

Thanks a lot in advance!

Drew
  • 111
  • 3
  • 10

2 Answers2

3

It's an array of objects, so you search through the array to find an object whose .firstName property matches your desired name.

Then, you see if that same matching object has a property with the other name passed in such as "likes".

function lookUp(fname, prop) {
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === fname) {
            return contacts[i][prop];
        }
    }
    return null;
}

lookUp("Akira", "likes");   // returns ["Pizza", "Coding", "Brownie Points"]
lookUp("Drew", "like");     // returns null (because name doesn't exist)
lookup("Akira", "address"); // returns undefined (because property doesn't exist)

If the passed in prop argument does not exist as a property on the matched object, then this will return undefined. If the firstName is not found as a match, this returns null. If you want a different return value for that, then you can test the return value before returning it and change the return result when the property is missing to whatever you want. Or, you can just have the caller test the return value and act accordingly (which is how this is written).


If you really want to return "No such property" when the property is missing and "No such contact" when the contact is not found, you can do that like this:

function lookUp(fname, prop) {
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === fname) {
            return contacts[i][prop] || "No such property";
        }
    }
    return "No such Contact";
}

But, note that it's highly unusual to return an array in one case and a string another time. You are forcing the caller to test the type of the return value in order to know how to properly use it. This is not typical in Javascript programming.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Hi. Thanks for the help. I would like to return the string value of "No such contact" when the name is not in the contact; and "No such property" when the value does not exist; However it seems my else if statements "block" the loop on its first iteration. Please help – Drew Mar 22 '16 at 08:54
  • code here: https://jsfiddle.net/frempong69/ws5c6obh/ – Drew Mar 22 '16 at 09:09
  • @Drew - See what I added to my answer in response to your specific request, but returning an array in one code path and a string in other code paths is usually not considered a good design practice. – jfriend00 Mar 22 '16 at 09:23
  • Oh okay. Well that's great, thanks! – Drew Mar 22 '16 at 09:54
0

You have two options. One of them is a for loop to loop through the list of contacts, but you can also use Array.prototype.find if you prefer to do this functionally. What this is doing is looping through the array until the correct condition is met by the callback given. More legible than using for loops, but the performance isn't quite the same.

ES5

// Callback for the next function
function lookup(firstName, prop) {
    var tarContact = contacts.find(function (contact) {
        return contact.name === firstName;
    });

    return tarContact && tarContact[prop];
});

function lookup(firstName, prop) {
    for (var i = 0; i < contacts.length; i++) {
        var contact = contacts[i];
        if (contact.name === firstName) {
            return contact && contact[prop];
        }
    }

    return;
}

ES6

const lookup = (firstName, prop) => {
    let tarContact = contacts.find((contact) => contact.name === firstName);
    return tarContact && tarContact[prop];
}

const lookup = (firstName, prop) => {
    for (let contact of contacts) {
        if (contact.name === firstName) {
            return contact && contact[prop];
        }
    }

    return;
}
kpimov
  • 13,632
  • 3
  • 12
  • 18