Tell us what’s happening:
How do I access an object’s properties using bracket notation if the object is inside an array?
I know this:
myObj = {prop1 : value1}
myObj[prop1] //; value1
But what if it’s an object within an array?
Your code so far
//Setup
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){
// Only change code below this line
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup
You would want to access it like this (assuming you know the index of the array where the object is:
let array = [ {prop1: "foo"} ];
array[0]["prop1"]; // "foo"
Don’t forget the quotes around prop1!
1 Like
How do I access the object property within an array using a for loop?
It depends on what the contents of the array are that you are looping through. If the array contains elements that are all the same object (just different values for the properties) then you can use the same syntax as I provided above, just replace the array index with a counter:
let array = [ {prop1: "foo"} {prop1: "bar"} ];
for(let index=0; index < array.length; index++){
console.log(array[index]["prop1"]) // prints "foo" first time, then "bar" second time
}
1 Like
I thought in this case it was different objects with properties. They appear to be different objects, not all the same.
In the example that you gave in your original post, the array consists all of objects that have the same properties people with a “firstName”, “lastName”, “number”, and "likes’. The values of those properties are what are different from person to person.
1 Like
So if all objects have the same property names, they’re all considered one object? Making sure I understand
They would all be considered to be the same object type. Sorry, I think I am getting ahead of myself as far as the exercise is concerned. I think it will make more sense to you once you learn about Classes and Inheritance later on 
1 Like
Ok. By the way.
Is this: ```
contacts[x].firstName
The same syntax as what you provided but instead using both bracket and dot notation?