The goal of this code is to find cats with a “talkative” personality and create an array of their names — but the error code won’t do the trick.
Code with error
const cats = {
moxie: {
color: "calico",
personality: "talkative",
},
gus: {
color: "orange",
personality: "mellow",
},
};
const talkativeCatNames = Object.keys(cats).filter(
(catName) => cats.catName.personality === "talkative"
);Corrected code
const cats = {
moxie: {
color: "calico",
personality: "talkative",
},
gus: {
color: "orange",
personality: "mellow",
},
};
const talkativeCatNames = Object.keys(cats).filter(
(catName) => cats[catName].personality === "talkative"
);Explanation
cats.catName.personality expects to find a key in the cats object that matches the string "catName". In this case, there is no key "catName" (only the keys "moxie" and "gus"). So cats.catName evaluates to undefined, and cats.catName.personality results in a TypeError:
Uncaught TypeError: Cannot read properties of undefined (reading 'personality')To access the value of catName as the property, we need to use bracket notation : cats[catName].personality.
Alternative solution
You could also solve this using Object.entries() instead of Object.keys(), but it’s a bit more involved:
Corrected code
const cats = {
moxie: {
color: "calico",
personality: "talkative",
},
gus: {
color: "orange",
personality: "mellow",
},
};
const talkativeCatEntries = Object.entries(cats).filter(
([catName, catProperties]) =>
catProperties.personality === "talkative");
const talkativeCatNames = talkativeCatEntries.map(
([catName, catProperties]) => catName);Further Reading
- The MDN Property Accessors article discusses dot notation vs. bracket notation
- MDN Object.keys() , Object.values() and Object.entries()