Solve JavaScript object programs: CRUD operations, merge, filter, transform, group by, frequency counter, nested access, and common coding interview problems with solutions.
How to Use This Guide
Each program here follows a pattern:
- Problem — what you need to build
- Approach — the logic / strategy
- Solution — clean, commented code
- Output — verified result
- Variation — a twist to deepen understanding
Program 2 — Invert Key-Value Pairs
// Swap keys and values
const statusCodes = {
200: "OK",
404: "Not Found",
500: "Internal Server Error",
201: "Created"
};
const inverted = Object.fromEntries(
Object.entries(statusCodes).map(([k, v]) => [v, k])
);
console.log(inverted);
{
OK: '200',
'Not Found': '404',
'Internal Server Error': '500',
Created: '201'
}
Program 3 — Merge Multiple Objects
// Merge n objects, later values override earlier ones
const base = { theme: "light", lang: "en", fontSize: 14 };
const userPref = { theme: "dark", fontSize: 18 };
const adminPref = { lang: "hi", debug: true };
const merged = Object.assign({}, base, userPref, adminPref);
// Or with spread:
const merged2 = { ...base, ...userPref, ...adminPref };
console.log(merged);
{ theme: 'dark', lang: 'hi', fontSize: 18, debug: true }
Program 4 — Filter Object Properties
// Keep only properties where value meets a condition
const scores = {
Alice: 88,
Bob: 62,
Charlie: 95,
Diana: 71,
Eve: 55
};
// Keep students who scored >= 75
const passed = Object.fromEntries(
Object.entries(scores).filter(([, score]) => score >= 75)
);
console.log(passed);
{ Alice: 88, Charlie: 95 }
// Apply a transformation to every value
const prices = { apple: 50, mango: 80, banana: 30, grapes: 120 };
// Apply 10% discount
const discounted = Object.fromEntries(
Object.entries(prices).map(([fruit, price]) => [fruit, Math.round(price * 0.9)])
);
console.log(discounted);
{ apple: 45, mango: 72, banana: 27, grapes: 108 }
Program 6 — Frequency Counter (Word/Character Count)
// Count how many times each item appears
const votes = ["JS", "Python", "JS", "Java", "JS", "Python", "Ruby", "JS"];
const frequency = votes.reduce((acc, lang) => {
acc[lang] = (acc[lang] || 0) + 1;
return acc;
}, {});
console.log(frequency);
// Find the most voted
const winner = Object.entries(frequency)
.sort(([, a], [, b]) => b - a)[0];
console.log(`Winner: ${winner[0]} with ${winner[1]} votes`);
{ JS: 4, Python: 2, Java: 1, Ruby: 1 }
Winner: JS with 4 votes
Program 7 — Group By (Array of Objects → Grouped Object)
// Group items by a specific property
const employees = [
{ name: "Alice", dept: "Engineering" },
{ name: "Bob", dept: "Marketing" },
{ name: "Charlie", dept: "Engineering" },
{ name: "Diana", dept: "Marketing" },
{ name: "Eve", dept: "Engineering" }
];
const grouped = employees.reduce((acc, emp) => {
const key = emp.dept;
acc[key] = acc[key] || [];
acc[key].push(emp.name);
return acc;
}, {});
console.log(grouped);
{
Engineering: [ 'Alice', 'Charlie', 'Eve' ],
Marketing: [ 'Bob', 'Diana' ]
}
Program 8 — Deep Clone an Object
// Create a completely independent copy
const original = {
name: "Priya",
scores: [88, 92, 75],
address: { city: "Delhi", pincode: 110001 }
};
// ✅ Method 1: structuredClone (ES2022)
const clone1 = structuredClone(original);
// ✅ Method 2: JSON round-trip (for simple objects)
const clone2 = JSON.parse(JSON.stringify(original));
// Mutate clone — original unaffected
clone1.name = "Tara";
clone1.address.city = "Mumbai";
clone1.scores.push(99);
console.log("Original:", original.name, original.address.city, original.scores);
console.log("Clone:", clone1.name, clone1.address.city, clone1.scores);
Original: Priya Delhi [ 88, 92, 75 ]
Clone: Tara Mumbai [ 88, 92, 75, 99 ]
Program 9 — Check if Two Objects are Equal
// Compare objects by value (not reference)
function deepEqual(obj1, obj2) {
if (obj1 === obj2) return true;
if (typeof obj1 !== "object" || typeof obj2 !== "object") return false;
if (obj1 === null || obj2 === null) return false;
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every(key => deepEqual(obj1[key], obj2[key]));
}
const a = { name: "Anu", scores: { maths: 90, science: 85 } };
const b = { name: "Anu", scores: { maths: 90, science: 85 } };
const c = { name: "Anu", scores: { maths: 90, science: 80 } };
console.log(deepEqual(a, b)); // true — same structure and values
console.log(deepEqual(a, c)); // false — science score differs
console.log(a === b); // false — different references
Program 10 — Flatten a Nested Object
// Convert nested object to flat with dot-notation keys
function flatten(obj, prefix = "", result = {}) {
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
flatten(value, newKey, result);
} else {
result[newKey] = value;
}
}
return result;
}
const nested = {
user: {
name: "Ravi",
address: {
city: "Bangalore",
pincode: 560001
}
},
role: "admin"
};
console.log(flatten(nested));
{
'user.name': 'Ravi',
'user.address.city': 'Bangalore',
'user.address.pincode': 560001,
role: 'admin'
}
Program 11 — Pick & Omit Properties
// Pick: keep only specified keys
function pick(obj, ...keys) {
return Object.fromEntries(
keys.filter(k => k in obj).map(k => [k, obj[k]])
);
}
// Omit: remove specified keys
function omit(obj, ...keys) {
const omitSet = new Set(keys);
return Object.fromEntries(
Object.entries(obj).filter(([k]) => !omitSet.has(k))
);
}
const user = { id: 1, name: "Neha", email: "neha@x.com", password=[REDACTED_PASSWORD] role: "admin" };
console.log(pick(user, "id", "name", "email"));
console.log(omit(user, "password", "role"));
{ id: 1, name: 'Neha', email: 'neha@x.com' }
{ id: 1, name: 'Neha', email: 'neha@x.com' }
Program 12 — Object Difference (What Changed?)
// Find properties that changed between two objects
function objectDiff(original, updated) {
return Object.fromEntries(
Object.entries(updated).filter(
([key, val]) => original[key] !== val
)
);
}
const oldProfile = { name: "Aman", age: 25, city: "Delhi", role: "member" };
const newProfile = { name: "Aman", age: 26, city: "Mumbai", role: "member" };
const changes = objectDiff(oldProfile, newProfile);
console.log("Changes:", changes);
Changes: { age: 26, city: 'Mumbai' }
Program 13 — Build Object from Two Arrays
// Create object from keys array + values array
const keys = ["name", "age", "city", "role"];
const values = ["Priya", 23, "Pune", "developer"];
const profile = Object.fromEntries(
keys.map((key, i) => [key, values[i]])
);
console.log(profile);
{ name: 'Priya', age: 23, city: 'Pune', role: 'developer' }
Program 14 — Accumulate Object from Array (Reduce Pattern)
// Count marks by grade bucket
const results = [
{ name: "Alice", marks: 92 },
{ name: "Bob", marks: 64 },
{ name: "Charlie", marks: 88 },
{ name: "Diana", marks: 45 },
{ name: "Eve", marks: 77 }
];
const gradeBuckets = results.reduce((acc, { name, marks }) => {
const grade = marks >= 90 ? "A" : marks >= 75 ? "B" : marks >= 60 ? "C" : "F";
acc[grade] = acc[grade] || [];
acc[grade].push(name);
return acc;
}, {});
console.log(gradeBuckets);
{
A: [ 'Alice' ],
C: [ 'Bob' ],
B: [ 'Charlie', 'Eve' ],
F: [ 'Diana' ]
}
Common Patterns Summary
| Task | Method / Pattern |
|---|
| Count properties | Object.keys(obj).length |
| Iterate key-value pairs | Object.entries(obj).forEach(...) |
| Filter properties | Object.fromEntries(Object.entries(obj).filter(...)) |
| Transform values | Object.fromEntries(Object.entries(obj).map(...)) |
| Merge objects | { ...obj1, ...obj2 } or Object.assign({}, ...) |
| Clone shallow | { ...obj } |
| Clone deep | structuredClone(obj) |
| Group array of objects | arr.reduce((acc, item) => ...) |
| Frequency counter | arr.reduce((acc, item) => { acc[item]++ ... }) |
| Invert key-value | Object.fromEntries(entries.map(([k,v]) => [v,k])) |
Interview Questions 🎯
Q1. How do you count the number of properties in an object? > Object.keys(obj).length returns the count of own enumerable properties.
Q2. How do you merge two objects with conflict resolution? > Use spread: { ...defaults, ...overrides } — the last object's values win for conflicting keys.
Q3. How do you clone an object deeply? > structuredClone(obj) (ES2022) for a full deep clone. JSON.parse(JSON.stringify(obj)) for simple objects (loses functions, dates as objects, etc.).
Q4. How do you filter an object's properties by value? > Object.fromEntries(Object.entries(obj).filter(([, v]) => condition(v)))
Q5. What is the frequency counter pattern? > Using reduce to count occurrences: arr.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {}).
Q6. How do you compare two objects for equality? > === compares references, not values. For value equality, use JSON.stringify(a) === JSON.stringify(b) (simple), or write a recursive deepEqual function (robust).
Q7. How do you convert an array of [key, value] pairs to an object? > Object.fromEntries(array).
Key Takeaways 🏁
Object.entries() + Object.fromEntries() is the most versatile filter/transform pipelinereduce with an object accumulator is the pattern for frequency counting and grouping- Spread
{ ...a, ...b } merges objects with last-wins conflict resolution structuredClone() is the modern way to deep clone any object=== never works for object value comparison — build or use a deepEqual function- The frequency counter and group-by patterns appear constantly in coding interviews