Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive string parsing into object - JavaScript
We are required to write a JavaScript function that takes in an array of strings and returns an object corresponding to the strings.
For example −
If the array is −
const arr = [ "country.UK.level.1", "country.UK.level.2", "country.US.level.1", "country.UK.level.3" ];
Then the output should be −
const output = {
"country": [
{"UK" : {"level" : ["1", "2", "3"]}},
{"US" : {"level" : ["1","2"]}}
]
}
Conditions
Strings stored in the str array will not be sorted and the code should be robust against that.
Strings will follow the x.y.x.y... pattern, where x will be unique for that array and y can change. In my example country and level will always be the same as they represent the x pos.
This requires recursive approach as the strings stored in the str array, can be of any length. The longer the string the deeper nesting.
Example
Following is the code −
const arr = [
"country.UK.level.1",
"country.UK.level.2",
"country.US.level.1",
"country.UK.level.3"
];
const stringToObject = arr => {
const obj = {};
arr.forEach(str => {
let curr = obj;
let splitted = str.split('.');
let last = splitted.pop();
let beforeLast = splitted.pop();
splitted.forEach( sub => {
if(!curr.hasOwnProperty(sub)){
curr[sub] = {};
};
curr = curr[sub];
});
if(!curr[beforeLast]){
curr[beforeLast] = [];
};
curr[beforeLast].push(last);
});
return obj;
};
console.log(JSON.stringify(stringToObject(arr), undefined, 4));
Output
This will produce the following output on console −
{
"country": {
"UK": {
"level": [
"1",
"2",
"3"
]
},
"US": {
"level": [
"1"
]
}
}
}Advertisements