Looping Through Objects
Objects aren't iterable like arrays, so you can't use for...of or map on them directly. Instead, JavaScript gives you static methods that turn an object into an array: Object.keys (the property names), Object.values (the values), and Object.entries ([key, value] pairs). Object.fromEntries turns pairs back into an object, and Object.groupBy (ES2024) builds a grouped object from an array in one call. With these, every array tool works on objects too.
In One Minute
Object.keys(obj),Object.values(obj),Object.entries(obj)return arrays of the object's own enumerable string-keyed properties.- Loop with
for (const [key, value] of Object.entries(obj)). - Transform an object:
Object.fromEntries(Object.entries(obj).map(...)). Object.groupBy(array, fn)groups items by the keyfnreturns.- To display an object, use
JSON.stringify(obj, null, 2)or the console.
Method Table
| Method | Description |
|---|---|
Object.keys(obj) | It is used to get an array of the object's own enumerable property names. |
Object.values(obj) | It is used to get an array of the property values. |
Object.entries(obj) | It is used to get an array of [key, value] pairs. |
Object.fromEntries(pairs) | It is used to build an object from [key, value] pairs (an array or a Map). |
Object.groupBy(items, fn) | It is used to group an iterable's items into an object by the key fn returns (ES2024). |
Map.groupBy(items, fn) | It is used to group items into a Map, allowing any key type (ES2024). |
Object.assign(target, ...sources) | It is used to copy properties into target (changes it). |
Keys, Values and Entries
const feesByItem = { tuition: 400, books: 85, lab: 45 };
console.log(Object.keys(feesByItem));
console.log(Object.values(feesByItem));
console.log(Object.entries(feesByItem));
const total = Object.values(feesByItem).reduce((sum, fee) => sum + fee, 0);
console.log(total, Object.keys(feesByItem).length);['tuition', 'books', 'lab']
[400, 85, 45]
[['tuition', 400], ['books', 85], ['lab', 45]]
530 3Because they return real arrays, everything from the arrays chapter applies: length counts the properties, reduce totals the values, filter selects entries.
Looping with for...of and Entries
const student = { name: "Advitha", grade: 9, city: "San Francisco" };
for (const [key, value] of Object.entries(student)) {
console.log(`${key.padEnd(6)} ${value}`);
}name Advitha
grade 9
city San FranciscoThese methods include only the object's own properties (not inherited ones) and only enumerable ones (the normal kind you create). That makes them safer than for...in, which also visits inherited enumerable properties.
Transforming Objects
Arrays have map and filter; objects don't. The pattern is: convert to entries, transform the array, convert back with Object.fromEntries:
const feesInDollars = { tuition: 400, books: 85.5, lab: 45 };
const feesInCents = Object.fromEntries(
Object.entries(feesInDollars).map(([item, dollars]) => [item, Math.round(dollars * 100)])
);
console.log(feesInCents);
const bigFees = Object.fromEntries(
Object.entries(feesInDollars).filter(([, dollars]) => dollars >= 50)
);
console.log(bigFees);
const swapped = Object.fromEntries(Object.entries({ a: "x", b: "y" }).map(([k, v]) => [v, k]));
console.log(swapped);{ tuition: 40000, books: 8550, lab: 4500 }
{ tuition: 400, books: 85.5 }
{ x: 'a', y: 'b' }Object.fromEntries also converts a Map or a URLSearchParams into a plain object, which is handy for form data and query strings.
Grouping with Object.groupBy
Grouping a list by some property is one of the most common data tasks. Object.groupBy (ES2024) does it in one call: it runs your function on each item and collects the items into arrays under the key the function returns:
const payments = [
{ name: "Navika", grade: 9, amount: 120 },
{ name: "Srihitha", grade: 11, amount: 85 },
{ name: "Advitha", grade: 9, amount: 45 },
{ name: "Zoe", grade: 12, amount: 300 },
];
const byGrade = Object.groupBy(payments, (p) => p.grade);
console.log(Object.keys(byGrade));
console.log(byGrade[9].map((p) => p.name));
const bySize = Object.groupBy(payments, (p) => (p.amount >= 100 ? "large" : "small"));
console.log(bySize.large.length, bySize.small.length);
const totals = Object.fromEntries(
Object.entries(byGrade).map(([grade, list]) => [grade, list.reduce((s, p) => s + p.amount, 0)])
);
console.log(totals);['9', '11', '12']
['Navika', 'Advitha']
2 2
{ 9: 165, 11: 85, 12: 300 }The returned object has a null prototype: it inherits nothing, not even toString, so group names like "constructor" can't collide with inherited properties. Map.groupBy works the same way but returns a Map, which keeps keys of any type (such as numbers or objects) without converting them to strings.
Displaying Objects
console.log shows objects in a readable form, but when you need an object as text (for a log file, a debug panel, or comparing two objects), use JSON.stringify:
const student = { name: "Navika", grade: 9, fees: [400, 85] };
console.log(JSON.stringify(student));
console.log(JSON.stringify(student, null, 2));
console.log(`Student: ${student}`);{"name":"Navika","grade":9,"fees":[400,85]}
{
"name": "Navika",
"grade": 9,
"fees": [
400,
85
]
}
Student: [object Object]Explanation: the third argument to JSON.stringify adds indentation. Putting an object directly into a template literal calls its default toString, which gives the unhelpful [object Object]. JSON.stringify skips functions, undefined values and symbol keys, and throws on circular references; the JSON lesson covers the details.
In Practice
The Fee Tracker's report groups payments by student, totals each group, and sorts the result by total, using entries to move between objects and arrays:
const payments = [
{ name: "Navika", amount: 120 },
{ name: "Advitha", amount: 45 },
{ name: "Navika", amount: 60 },
{ name: "Srihitha", amount: 85 },
{ name: "Advitha", amount: 200 },
];
const groups = Object.groupBy(payments, (p) => p.name);
const report = Object.entries(groups)
.map(([name, list]) => ({ name, total: list.reduce((s, p) => s + p.amount, 0), count: list.length }))
.toSorted((a, b) => b.total - a.total);
for (const { name, total, count } of report) {
console.log(`${name.padEnd(9)} $${String(total).padStart(4)} (${count})`);
}Advitha $ 245 (2)
Navika $ 180 (2)
Srihitha $ 85 (1)Common Mistakes
for...of directly on an object. TypeError: obj is not iterable. Loop over Object.entries(obj).
obj.length. Plain objects have no length. Use Object.keys(obj).length.
Expecting numeric keys to stay numbers. Keys from Object.keys and Object.entries are strings: "9", not 9. Convert with Number(key) when needed, or use Map.groupBy.
Logging objects inside template literals. You get [object Object]. Use JSON.stringify or pass the object as a separate console.log argument.
Practice
Challenge: Write mapValues(obj, fn) that returns a new object with the same keys and each value replaced by fn(value). Use it to add 5% to every fee.
Show solution
function mapValues(obj, fn) {
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
}
const fees = { tuition: 400, books: 80, lab: 40 };
console.log(mapValues(fees, (fee) => fee * 1.05));
console.log(fees);{ tuition: 420, books: 84, lab: 42 }
{ tuition: 400, books: 80, lab: 40 }Key Takeaways
| Task | Code |
|---|---|
| Property names | Object.keys(obj) |
| Sum of values | Object.values(obj).reduce((a, b) => a + b, 0) |
| Loop | for (const [k, v] of Object.entries(obj)) |
| Map values | Object.fromEntries(Object.entries(obj).map(...)) |
| Group an array | Object.groupBy(list, (x) => x.grade) |
Was this tutorial helpful?