1

Here is the code

var contacts = { //object
  "Father": {
    "Name": "X",
    "Age": "48",
    "phoneNumber": "99373xxxxx",
    "Likes": ["Cricket", "spicyFood"]
  },
  "Mother": {
    "Name": "Y",
    "Age": "39",
    "phoneNumber": "79788xxxxx",
    "Likes": ["comedyShows", "spicyFood"]
  },
  "Sister": {
    "Name": "Z",
    "Age": "8",
    "phoneNumber": "Not Available",
    "Likes": ["funnyVideos", "Sweets"]
  }

};

function lookUp(name, prop) {
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].Name === name) {
      return contacts[i][prop] || "No such property";
    };
  }
  return "No such value";
}
var data = lookUp("Z", "Likes");
console.log(data);

Whenever I compile the code, it returns "No such value", as if neglecting the for loop that was inserted. How to fix this?

James Z
  • 12,209
  • 10
  • 24
  • 44
ANM
  • 7
  • 7
  • 1
    Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – chazsolo Aug 23 '21 at 15:51

1 Answers1

0

contacts is an object, not an array.

You can use a for...in loop to iterate through each property:

var contacts = {
  "Father": {
    "Name": "X",
    "Age": "48",
    "phoneNumber": "9937368999",
    "Likes": ["Cricket", "spicyFood"]
  },
  "Mother": {
    "Name": "Y",
    "Age": "39",
    "phoneNumber": "7978869307",
    "Likes": ["comedyShows", "spicyFood"]
  },
  "Sister": {
    "Name": "Z",
    "Age": "8",
    "phoneNumber": "Not Available",
    "Likes": ["funnyVideos", "Sweets"]
  }
};

function lookUp(name, prop) {
  for(const key  in contacts){
    if (contacts[key].Name === name) {
      return contacts[key][prop] || "No such property";
    };
  }
  return "No such value";
}
var data = lookUp("Z", "Likes");
console.log(data);
Spectric
  • 30,714
  • 6
  • 20
  • 43