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
Constructing a nested JSON object in JavaScript
In JavaScript, we often need to construct nested objects from structured data. This article demonstrates how to build a nested JSON object from a string containing paired characters.
Problem Statement
Given a string with characters in pairs, we need to construct a nested object where each pair becomes a code property, and each level has a sub-object for the next pair.
Input string:
const str = "AABBCCDDEE";
Expected output structure:
const obj = {
code: "AA",
sub: {
code: "BB",
sub: {
code: "CC",
sub: {
code: "DD",
sub: {
code: "EE",
sub: {}
}
}
}
}
};
Solution Approach
We'll use an iterative approach to process the string in pairs of two characters. For each pair, we create a code property and prepare a sub object for the next iteration.
Implementation
const str = "AABBCCDDEE";
const constructObject = str => {
const res = {};
let ref = res;
while(str) {
const words = str.substring(0, 2);
str = str.substring(2);
ref.code = words;
ref.sub = {};
ref = ref.sub;
}
return res;
};
console.log(JSON.stringify(constructObject(str), null, 2));
{
"code": "AA",
"sub": {
"code": "BB",
"sub": {
"code": "CC",
"sub": {
"code": "DD",
"sub": {
"code": "EE",
"sub": {}
}
}
}
}
}
How It Works
The algorithm works by:
- Creating an initial empty object
resand a reference pointerref - Iterating through the string, extracting 2 characters at a time
- Setting the
codeproperty to the current pair - Creating an empty
subobject for the next iteration - Moving the reference pointer to the new
subobject
Alternative Implementation
Here's a recursive version for comparison:
const constructObjectRecursive = (str, index = 0) => {
if (index >= str.length) {
return {};
}
return {
code: str.substring(index, index + 2),
sub: constructObjectRecursive(str, index + 2)
};
};
const str2 = "XXYYZZ";
console.log(JSON.stringify(constructObjectRecursive(str2), null, 2));
{
"code": "XX",
"sub": {
"code": "YY",
"sub": {
"code": "ZZ",
"sub": {}
}
}
}
Conclusion
Both iterative and recursive approaches can construct nested JSON objects from paired character strings. The iterative method is more memory-efficient, while the recursive approach offers cleaner, more readable code for this pattern.
