Access array inside nested object [solved]

I am working on the weather project and I am trying to access elements of an array stored inside a nested object in order to dynamically set the background based on the weather conditions. My code:

function selectBackgroundPhoto(code) {
  var photos = {
    fog: {codes: [1030, 1135, 1147], url: ""},
    partlycloudy: {codes: [1003], url: ""},
    cloudy: {codes: [1006, 1009], url: ""},
    sunny: {codes: [1000], url: ""},
    rain: {codes: [1063, 1087, 1150, 1153, 1180, 1183, 1186, 1189, 1192, 1195, 1240, 1243, 1246, 1273, 1276], url: ""},
    sleet: {codes: [1069, 1072, 1168, 1171, 1198, 1201, 1204, 1207, 1237, 1249, 1252, 1261, 1264], url: ""}}
  for (var prop in photos) {
    if (photos.hasOwnProperty(prop)) {
      if ( !== undefined) {
        return prop.url;

I have been investigating dot vs. bracket notation for accessing properties, and with my current understanding I think it is set up correctly on that front. I receive a TypeError: is not defined when I run the code. What is incorrect?

Try changing to photos[prop].codes.find(code) in the for loop. You’ll also need to return photos[prop].url instead of prop.url.

When you iterate over an object’s properties, you’re only getting the property name, not the actual object property. You need to actually access the property, in this case with photos[prop].

Ah, okay. I find that my confusion about correctness is tied in with my misuse of the Array.prototype.find() function. Thanks for helping me fix my access notation!

Hello there!

I think there are a few issues with your for loop. To begin with, you are already looping through each item in the for loop with for (var prop in photos)—the condition in the next if line is unnecessary and will always return true because prop is already something that can only exist in photo. Try the following code blocks and you will see what I mean:

for (var prop in photos)  {
  console.log(prop); // Returns "fog", "partlycloudy", "cloudy", "sunny", "rain", "sleet"

The second problem that the way you used find() is not how find() is used—please have a look at the MDN documentation for more information (link). Try this example and you will see what I mean:

console.log([1, 2, 3, 4, 5].find((element) => {return element > 3}));

indexOf() is probably what you are after.

Good luck! :slight_smile:

EDIT: Looks like I was just a tad too late. :frowning: