//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
];
function lookUpProfile(name, prop) {
for (var x = 0; x < contacts.length; x++) {
if (name === contacts[x].firstName) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
// Change these values to test your function
console.log(lookUpProfile("Akira", "likes"));
****
I know all other codes, but why it returned the prop var and x like a two dimensional array?
It's not returning x and prop
The code executes a for loop over the array. The array is an array of Objects
If name - the first variable that is being taken in equals the firstName at the current (x) iteration of the loop AND if the current iteration of the loop contains a key (prop) == "likes" then return the value for that key (prop)
"x" is the current index of the loop through the array, "prop" is the key of the value of the object that is to be returned.
Mayank Dubey
Passionate Programmer
Contacts var is an array of objects. Variable x is used to access object at index x and prop var is used to access property inside the object at index 'x'. In javascript objects, properties can be accessed using two ways: dot notation or bracket notation. For dot notation, property must be a valid javascript identifier. For bracket notation, it should be a string (or symbol ). As prop variable is a string we can access its value using bracket notation.
You can learn more about property accessing in javascript objects here