0
//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(firstNames, prop){
// Only change code below this line

  for (var i=0; i<contacts.length; i++){
    if(contacts[i].firstName == firstNames){
      for (var j=0; j<contacts[i].length; j++){
        if(contacts[i][j] == prop){
          return contacts[i][j].prop;
        } else {
          return "No such property";
        }
      }
    } else{
       return "No such contact";
    }

  }
  // Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

The above code doesn't work, specifically on the line with the for (var j=0; j<contacts[i].length; j++) line, as contacts[i].length is undefined, when I ran console.log statements into my code

How exactly do you define the length of an javascript object that is nested inside of another object?

reference example https://www.freecodecamp.org/challenges/profile-lookup

Vincent Tang
  • 3,758
  • 6
  • 45
  • 63
  • No need to iterate all the object keys ... just use [Object#hasOwnProperty()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) – charlietfl Jul 08 '17 at 14:39
  • var myCount = 0; myItems.forEach(i => myCount += i.myNestedArray.length); – R-D Jan 21 '21 at 15:32

1 Answers1

1

The Object prototype does not define a length function, that is why it is undefined. However, you can get an array of every (own) property key in your object using Object.keys:

var props = Object.keys(contracts[i]);

for (var j = 0; j < props.length; j++) {
  // etc.
}
Mate Solymosi
  • 5,699
  • 23
  • 30