How to Flatten Object in JavaScript: Simple Guide
To flatten an object in JavaScript, you can use a recursive function that iterates through nested objects and creates a new object with dot-separated keys using
Object.keys() and recursion. This converts deep nested structures into a single-level object with combined keys.Syntax
The basic syntax involves a function that takes an object and a prefix string (for nested keys) and returns a new flattened object. It uses Object.keys() to loop through keys and recursion to handle nested objects.
obj: The object to flatten.prefix: A string to prepend to keys for nested objects.- Returns a new object with flattened keys.
javascript
function flattenObject(obj, prefix = '') { return Object.keys(obj).reduce((acc, key) => { const value = obj[key]; const prefixedKey = prefix ? `${prefix}.${key}` : key; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { Object.assign(acc, flattenObject(value, prefixedKey)); } else { acc[prefixedKey] = value; } return acc; }, {}); }
Example
This example shows how to flatten a nested object with multiple levels. The output is a single-level object with keys joined by dots.
javascript
const nested = { user: { name: 'Alice', address: { city: 'Wonderland', zip: 12345 } }, active: true }; const flat = flattenObject(nested); console.log(flat);
Output
{"user.name":"Alice","user.address.city":"Wonderland","user.address.zip":12345,"active":true}
Common Pitfalls
Common mistakes include:
- Not checking if a value is an object before recursing, which can cause errors on
nullor arrays. - Flattening arrays as objects, which may not be desired.
- Overwriting keys if nested keys have the same name as top-level keys.
Always check for null and arrays explicitly.
javascript
function wrongFlatten(obj, prefix = '') { const result = {}; for (const key in obj) { const value = obj[key]; const newKey = prefix ? prefix + '.' + key : key; if (typeof value === 'object') { // Missing null and array check Object.assign(result, wrongFlatten(value, newKey)); } else { result[newKey] = value; } } return result; } // Correct way includes checks: function correctFlatten(obj, prefix = '') { return Object.keys(obj).reduce((acc, key) => { const value = obj[key]; const newKey = prefix ? `${prefix}.${key}` : key; if (typeof value === 'object' && value !== null && !Array.isArray(value)) { Object.assign(acc, correctFlatten(value, newKey)); } else { acc[newKey] = value; } return acc; }, {}); }
Quick Reference
- Use recursion to handle nested objects.
- Check for
nulland arrays to avoid errors. - Use dot notation to join keys.
- Return a new object to avoid mutating the original.
Key Takeaways
Flatten nested objects by recursively combining keys with dot notation.
Always check for null and arrays before recursing to avoid errors.
Return a new object to keep the original object unchanged.
Flattening helps simplify deep objects for easier access and manipulation.