Object-Based Coding Problems

You've learned how to create objects, read and update properties, write methods, destructure, copy, and use Object.keys, Object.values, and Object.entries. Now it's practice time! 💪

Objects are used everywhere in real apps: user profiles, shopping carts, orders, settings, and data from servers. Getting comfortable with them is one of the most useful skills in JavaScript.

How to Use This Lesson

For every problem:

  1. 📖 Read the problem and the example.
  2. 🤔 Think about the steps on paper first.
  3. ⌨️ Try your own code in the playground.
  4. ✅ Then check the solution.

Getting stuck is normal. The learning happens when you try first. 🙌

Your Object Toolbox 🧰

Most object problems are solved with these few tools:

ToolWhat it does
for...inLoop through the keys
Object.keys(obj)Get an array of keys
Object.values(obj)Get an array of values
Object.entries(obj)Get [key, value] pairs
Object.fromEntries(pairs)Turn pairs back into an object
obj[key]Read or write a key stored in a variable
key in objCheck if a key exists
{ ...obj }Make a copy

🟢 Level 1: Easy

Problem 1: Count the Properties

Task: Find how many details a product has.

Input: { name: "Laptop", brand: "Dell", ram: "16GB", price: 55000 }Output: 4

💡 Idea: Get all the keys as an array, then check its length.


Problem 2: Sum of All Values

Task: Find the total monthly expenses.

Input: { rent: 12000, food: 6000, travel: 2000, phone: 500 }Output: Total: ₹20500

💡 Idea: Take all the values as an array, then add them up.


Problem 3: Find the Highest Value

Task: Find the subject with the highest marks.

Input: { Maths: 88, Science: 95, English: 76, Hindi: 82 }Output: Top subject: Science (95)

💡 Idea: Keep track of the best subject so far. Update it whenever you find higher marks.


Problem 4: Check If a Key Exists

Task: Check if a user has added a phone number to their profile.

Input: { name: "Neha", email: "[email protected]" }, key: "phone"Output: Phone not added ❌

💡 Idea: Use the in operator or Object.hasOwn(). Don't just check the value, because a value like 0 or "" would look "missing."


Problem 5: Print an Object Nicely

Task: Print a restaurant bill from a menu order.

Input: { "Paneer Tikka": 280, "Butter Naan": 60, "Lassi": 80 }Output:

Paneer Tikka ....... ₹280
Butter Naan ........ ₹60
Lassi .............. ₹80

💡 Idea: Loop through the pairs. Use padEnd() to line up the dots.


🟡 Level 2: Medium

Problem 6: Count Characters in a Word

Task: Count how many times each letter appears.

Input: "banana"Output: { b: 1, a: 3, n: 2 }

💡 Idea: Use an object like a tally sheet ✍️. For each letter, add 1 to its count.

How (count[letter] || 0) + 1 works:

  • First time we see "a" → count["a"] is undefined → undefined || 0 gives 0 → 0 + 1 = 1
  • Next time → count["a"] is 1 → 1 + 1 = 2

Problem 7: Swap Keys and Values

Task: Turn a "state → capital" object into "capital → state".

Input: { Maharashtra: "Mumbai", Karnataka: "Bengaluru", Bihar: "Patna" }Output: { Mumbai: "Maharashtra", Bengaluru: "Karnataka", Patna: "Bihar" }

💡 Idea: For each pair, make the value the new key and the key the new value.


Problem 8: Filter an Object

Task: Keep only the items that are in stock.

Input: { Rice: 50, Sugar: 0, Dal: 20, Oil: 0, Salt: 35 }Output: { Rice: 50, Dal: 20, Salt: 35 }

💡 Idea: Objects don't have a filter() method, but arrays do! Convert to pairs, filter them, then convert back.

Object → entries → filter → fromEntries → Object

Problem 9: Merge Two Objects

Task: Combine the default app settings with the user's choices. The user's choices should win.

Input: defaults { theme: "light", language: "English", notifications: true }, user { theme: "dark", language: "Hindi" }Output: { theme: "dark", language: "Hindi", notifications: true }

💡 Idea: Use spread .... When the same key appears twice, the later one wins.


Problem 10: Group Items by a Property

Task: Group students by their city.

Input:

[
  { name: "Aarav", city: "Delhi" },
  { name: "Diya", city: "Pune" },
  { name: "Kabir", city: "Delhi" },
  { name: "Meera", city: "Pune" },
  { name: "Rohan", city: "Jaipur" }
]

Output: { Delhi: ["Aarav", "Kabir"], Pune: ["Diya", "Meera"], Jaipur: ["Rohan"] }

💡 Idea: For each student, check if their city already has a list. If not, create an empty list first. Then add the name.


Problem 11: Shopping Cart Total 🛒

Task: Find the total bill of a cart, where each item has a price and a quantity.

Input:

[
  { item: "Shoes", price: 1999, qty: 1 },
  { item: "Socks", price: 199, qty: 3 },
  { item: "Cap", price: 499, qty: 2 }
]

Output: Total: ₹3594

💡 Idea: For each item, multiply the price by the quantity, then add everything up.


Problem 12: Remove Empty Values

Task: Clean up a form by removing fields that are empty, null, or undefined.

Input: { name: "Ravi", email: "", phone: null, city: "Pune", pincode: undefined, age: 0 }Output: { name: "Ravi", city: "Pune", age: 0 }

💡 Idea: Keep a field only if its value is not "", null, or undefined. Be careful: 0 is a real value, so don't remove it!

value != null (with two =) is a handy shortcut that checks for both null and undefined.


🔴 Level 3: Interview Favourites

Problem 13: Check If Two Words Are Anagrams ⭐

Task: Two words are anagrams if they have the same letters, just in a different order.

Input: "listen" and "silent"Output: true

💡 Idea: Count the letters in both words using objects (like Problem 6). If both counts match, they are anagrams.


Problem 14: First Non-Repeating Character

Task: Find the first letter that appears only once.

Input: "aabbcdeec"Output: "d"

💡 Idea: First, count every letter. Then go through the word again and return the first letter whose count is 1.


Problem 15: Deep Compare Two Objects

Task: Check if two objects have exactly the same keys and values, even nested ones.

💡 Why not ===? Because === checks if they are the same object in memory, not whether their contents are equal.

💡 Idea:

  1. If both values are not objects, compare them with ===.
  2. If they have a different number of keys, they are not equal.
  3. Otherwise, compare each key's value using the same function (recursion).

Problem 16: Get a Nested Value from a Path

Task: Read a deep value using a path string like "customer.address.city".

Input: order object, path: "customer.address.city"Output: "Jaipur"

💡 Idea: Split the path by ".", then go one step deeper for each part. If any step is missing, return undefined instead of crashing.


Problem 17: Flatten a Nested Object

Task: Turn a nested object into a flat one, with dotted keys.

Input: { name: "Amit", address: { city: "Pune", pin: { code: 411001 } } }Output: { name: "Amit", "address.city": "Pune", "address.pin.code": 411001 }

💡 Idea: Go through each key. If the value is an object, flatten it too (recursion), adding the parent key in front with a dot.


Problem 18: Most Frequent Item

Task: Find the most ordered dish in a restaurant. 🍽️

Input: ["Biryani", "Dosa", "Biryani", "Paneer", "Dosa", "Biryani"]Output: Most ordered: Biryani (3 times)

💡 Idea: Count every dish (like Problem 6), then find the one with the highest count (like Problem 3). Two easy problems combined into one! 🧩


🎯 Practice Challenges (Try Yourself!)

No solutions here. Try them in the playground! 💪

  1. Invert and group: { a: "x", b: "y", c: "x" } → { x: ["a", "c"], y: ["b"] }
  2. Pick keys: Write pick(obj, ["name", "age"]) that returns a new object with only those keys.
  3. Omit keys: Write omit(obj, ["password"]) that returns a copy without those keys.
  4. Word count: Count how many times each word appears in "the cat and the hat and the bat".
  5. Price hike: Increase every price in { milk: 60, bread: 40 } by 10% and round the result.
  6. Unflatten: Turn { "a.b": 1, "a.c": 2 } back into { a: { b: 1, c: 2 } }.

Common Patterns You Just Learned

PatternUsed inIdea
Tally objectCount letters, anagram, most frequentcount[x] = (count[x] || 0) + 1
Track the bestHighest value, most frequentRemember the best key and value so far
entries → array method → fromEntriesFilter, swap, cleanUse array tools on objects
Group into listsGroup by cityCreate an empty list first, then push
Spread mergeSettings{ ...defaults, ...choices }
RecursionDeep compare, flattenHandle a nested object with the same function
Safe path walkingGet nested valueUse ?. at every step

Tips for Solving Object Problems

  • ✅ Remember: objects don't have map, filter, or reduce. Use Object.entries() first, then convert back with Object.fromEntries().
  • ✅ Use bracket notation obj[key] when the key is in a variable.
  • ✅ Use in or Object.hasOwn() to check if a key exists, not the value.
  • ✅ Test with edge cases: an empty object {}, missing keys, 0, "", and null values.
  • ✅ Use console.log() inside your loops to see what's happening at each step.

Key Takeaways

  • Most object problems use a few patterns: tally objects, tracking the best value, grouping, merging, and converting with entries/fromEntries.
  • A tally object count[x] = (count[x] || 0) + 1 solves counting, anagram, and most-frequent problems.
  • To filter or transform an object, go object → entries → array method → fromEntries → object.
  • === compares objects by reference, not content, so write a deep compare to check if contents match.
  • Big problems are often two small problems combined, like counting first and then finding the highest. 🧩