For Given a string with keys separated by dots, the following code constructs a
nested object based on those keys.
input "a.b.c.d.e.f" requied output:
{
"a": {
"b": {
"c": {
"d": {
"e": "f"
}
}
}
}
}
Code:
const str = "a.b.c.d.e.f";
const arr = str.split(".");
function getDesiredObject(arr) {
if (arr.length === 2) {
return {
[arr[0]]: arr[1]
};
}
return {
[arr[0]]: getDesiredObject(arr.slice(1))
};
}
let result = getDesiredObject(arr);
console.log(JSON.stringify(result, null, 2));
Output:
{
"a": {
"b": {
"c": {
"d": {
"e": "f"
}
}
}
}
}
Explanation:
1. The code defines a string `str` that contains a series of keys separated by dots.
It then splits this string into an array `arr` using the dot as a delimiter.
2. The function `getDesiredObject` takes this array and recursively constructs a
nested object based on the keys in the array.
3. If the array has only two elements, it creates an object with the first element
as the key and the second element as the value.
4. If the array has more than two elements, it creates an object with the first
element as the key and calls itself recursively with the rest of the array to
build the nested structure.
5. Finally, the resulting object is logged to the console in a formatted JSON string.
No comments:
Post a Comment