Access array inside nested object [solved]

Access array inside nested object [solved]
0

#1

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: "https://s24.postimg.org/owuib3pn5/mist.jpg"},
    partlycloudy: {codes: [1003], url: "https://s24.postimg.org/6rhjx1q4x/Cloudy_sky_Turkey.jpg"},
    cloudy: {codes: [1006, 1009], url: "https://s24.postimg.org/ebamz3jbl/nubes-grises.jpg"},
    sunny: {codes: [1000], url: "https://s24.postimg.org/tmkfzpgnl/sky-sunny-clouds-cloudy.jpg"},
    rain: {codes: [1063, 1087, 1150, 1153, 1180, 1183, 1186, 1189, 1192, 1195, 1240, 1243, 1246, 1273, 1276], url: "https://s24.postimg.org/daae9z2c1/rain-455120_960_720.jpg"},
    sleet: {codes: [1069, 1072, 1168, 1171, 1198, 1201, 1204, 1207, 1237, 1249, 1252, 1261, 1264], url: "https://s24.postimg.org/m7v47bus1/sleet.jpg"}}
  
  for (var prop in photos) {
    if (photos.hasOwnProperty(prop)) {
      if (prop.codes.find(code) !== 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: prop.codes is not defined when I run the code. What is incorrect?


#2

Try changing prop.codes.find(code) 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].


#3

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!


#4

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: