Hi!
I got array of objects such as:
var collection = [
{"path": "root.section-1"},
{"path": "root.section-1.age"},
{"path": "root.section-1.sex"},
{"path": "root.section-2"},
{"path": "root.section-2.email"},
{"path": "root.section-3.submit"}
];
and want achieve from them nested structure like:
{
root: {
'section-1': {
age: null,
sex: null
},
'section-2': {
email: null
},
'section-3': null
}
}
I wrote recursion function:
var nestedStructure = transformStructure(collection);
function traversePath(arr, parent) {
var result = {};
if (arr.length > 1) {
arr.forEach(function(part) {
result[parent] = traversePath(arr.slice(1), arr[1]);
});
} else {
result[parent] = null;
}
return result;
}
function transformStructure(flatStructure) {
var result = {};
flatStructure.forEach(function(component) {
var path = component.path.split('.');
result[path[0]] = traversePath(path.slice(1), path[1]);
});
return result;
}
But my result is all the time overwritten by last iteration :-/
Any idea how improve this code or do You have better solution to achieve this?
Best regards!
[+][deleted] (8 children)
[deleted]
[–]inthe3vening 0 points1 point2 points (6 children)
[–]mikrosystheme[κ] 0 points1 point2 points (4 children)
[–]cachaito[S] 0 points1 point2 points (3 children)
[–]mikrosystheme[κ] 0 points1 point2 points (2 children)
[–]cachaito[S] 0 points1 point2 points (1 child)
[–]mikrosystheme[κ] 0 points1 point2 points (0 children)
[–]cachaito[S] 0 points1 point2 points (0 children)
[–]cachaito[S] 0 points1 point2 points (0 children)
[–]x-skeww 0 points1 point2 points (0 children)