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
Convert a string to hierarchical object - JavaScript
Let's say, we have a special kind of string that contains characters in couples, like this:
const str = "AABBCCDDEE"; console.log(str);
AABBCCDDEE
We are required to construct an object based on this string which should look like this:
const obj = {
code: "AA",
sub: {
code: "BB",
sub: {
code: "CC",
sub: {
code: "DD",
sub: {
code: "EE",
sub: {}
}
}
}
}
};
Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple.
Using Iterative Approach
We can solve this problem using an iterative approach. We will iterate over the string to pick specific couples and assign a new sub object for each:
const str = "AABBCCDDEE";
const constructObject = str => {
const res = {};
let ref = res;
while(str) {
const words = str.substring(0, 2);
str = str.substr(2, str.length);
ref.code = words;
ref.sub = {};
ref = ref.sub;
}
return res;
};
console.log(JSON.stringify(constructObject(str), undefined, 4));
Output
{
"code": "AA",
"sub": {
"code": "BB",
"sub": {
"code": "CC",
"sub": {
"code": "DD",
"sub": {
"code": "EE",
"sub": {}
}
}
}
}
}
Using Recursive Approach
Alternatively, we can use a recursive solution for better readability:
const constructObjectRecursive = (str, index = 0) => {
if (index >= str.length) {
return {};
}
const code = str.substring(index, index + 2);
return {
code: code,
sub: constructObjectRecursive(str, index + 2)
};
};
const str2 = "XXYYZZ";
console.log(JSON.stringify(constructObjectRecursive(str2), undefined, 2));
{
"code": "XX",
"sub": {
"code": "YY",
"sub": {
"code": "ZZ",
"sub": {}
}
}
}
How It Works
The iterative approach works by:
- Creating an empty result object and maintaining a reference pointer
- Extracting two characters at a time using
substring(0, 2) - Setting the
codeproperty to the extracted couple - Creating a new empty
subobject for nesting - Moving the reference to the newly created sub object
Conclusion
Both iterative and recursive approaches effectively convert a paired character string into a hierarchical object structure. The iterative method is more memory-efficient for long strings, while recursion offers cleaner, more readable code.
