
JavaScript Object Methods - A Practical Guide
The Problem Imagine you have a pie recipe object from an API that looks like this: const pie = { name : " Apple Pie " , category : " Dessert " , servings : 8 , strIngredient1 : " Flour " , strIngredient2 : " Butter " , strIngredient3 : " Sugar " , strIngredient4 : " Apples " , strIngredient5 : null , strIngredient6 : null , strIngredient7 : null , step1 : " Mix dry ingredients " , step2 : " Add butter " , step3 : " Fill with apples " , step4 : null , step5 : null , }; How do you pull out just the ingredients that aren't null ? How do you grab just the steps? That's where object methods come in. 1. Object.keys() - Get All Property Names Returns an array of strings — every key in the object. Object . keys ( pie ); // ["name", "category", "servings", "strIngredient1", "strIngredient2", ...] Real use: Extract valid ingredients (what your project does) const ingredients = Object . keys ( pie ) . filter (( key ) => key . startsWith ( " strIngredient " ) && pie [ key ] !== null ) . map (( key
Continue reading on Dev.to JavaScript
Opens in a new tab


