Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Flattening a JSON object in JavaScript
Flattening a JSON object means converting a nested object structure into a single-level object where nested keys are represented using dot notation. This technique is useful for data processing, form handling, and API transformations.
Suppose we have the following JSON object that may contain nesting up to any level:
const obj = {
"one": 1,
"two": {
"three": 3
},
"four": {
"five": 5,
"six": {
"seven": 7
},
"eight": 8
},
"nine": 9
};
console.log("Original object:", obj);
Original object: {
one: 1,
two: { three: 3 },
four: { five: 5, six: { seven: 7 }, eight: 8 },
nine: 9
}
We need to write a JavaScript function that takes such a nested JSON object and returns a new object with no nesting, mapping values to keys using dot notation.
Expected Output Format
For the object above, the flattened output should look like this:
{
'one': 1,
'two.three': 3,
'four.five': 5,
'four.six.seven': 7,
'four.eight': 8,
'nine': 9
}
Implementation Using Recursion
Here's a recursive function to flatten the JSON object:
const obj = {
"one": 1,
"two": {
"three": 3
},
"four": {
"five": 5,
"six": {
"seven": 7
},
"eight": 8
},
"nine": 9
};
const flattenJSON = (obj = {}, res = {}, extraKey = '') => {
for(key in obj){
if(typeof obj[key] !== 'object' || obj[key] === null){
res[extraKey + key] = obj[key];
} else {
flattenJSON(obj[key], res, `${extraKey}${key}.`);
}
}
return res;
};
console.log(flattenJSON(obj));
{
one: 1,
'two.three': 3,
'four.five': 5,
'four.six.seven': 7,
'four.eight': 8,
nine: 9
}
How It Works
The function works by:
- Recursive traversal: It iterates through each key in the object
- Type checking: If a value is not an object (or is null), it's added to the result
- Key building: For nested objects, it builds the dot notation key by concatenating parent keys
- Base case: Non-object values stop the recursion and are stored directly
Alternative Implementation
Here's a cleaner version that handles edge cases better:
const flattenObject = (obj, prefix = '') => {
const flattened = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (obj[key] === null || typeof obj[key] !== 'object') {
flattened[newKey] = obj[key];
} else {
Object.assign(flattened, flattenObject(obj[key], newKey));
}
}
}
return flattened;
};
const testObj = {
name: "John",
address: {
street: "123 Main St",
city: "New York",
coordinates: {
lat: 40.7128,
lng: -74.0060
}
},
hobbies: ["reading", "coding"]
};
console.log(flattenObject(testObj));
{
name: 'John',
'address.street': '123 Main St',
'address.city': 'New York',
'address.coordinates.lat': 40.7128,
'address.coordinates.lng': -74.006,
hobbies: [ 'reading', 'coding' ]
}
Key Points
- The function handles nested objects of any depth
- Null values are treated as primitive values, not objects
- Arrays are preserved as-is rather than being flattened
- The dot notation creates a clear hierarchy representation
Conclusion
JSON flattening is a powerful technique for simplifying nested data structures. The recursive approach efficiently handles objects of any depth, making it useful for data transformation and API processing tasks.
