I'm looking for a way in which I can achieve the following transformation:
The following code contains the old + new structure:
function test_cleanHierarchyUp() {
console.log("Test for cleaning up hierarchy")
// I don't have children, so just keep me as is.
var bottom_level_object = {
'test': 'testest',
'more test': 'test',
'test': ''
}
var middle_object = {
children: bottom_level_object,
Name: "Middle Yeah!"
}
var original_object = [{
Name: "I am a name",
RandomName: '',
Children: middle_object
},
{
Name: "I am a name too",
Children: bottom_level_object
}
]
console.log("-----")
console.log("Source object: ")
console.log(original_object)
// Target structure:
// I don't have children, so just keep me as is.
var bottom_level_object_new = {
'test': 'testest',
'more test': 'test'
}
// Empty string (object 'Random') was removed from object.
var middle_object_new = {
"Middle Yeah!": {
children: bottom_level_object,
Name: "Middle Yeah!"
}
}
var target_object = {
"I am a name": {
Name: "I am a name",
Children: middle_object_new
},
"I am a name too": {
Name: "I am a name too",
Children: bottom_level_object_new
}
}
console.log("-----")
console.log("Target object: ")
console.log(target_object)
}
I did try: Recursion still hasn't dropped for me, unfortunately. A minor addition is in the code, in the same recursion function I'd like to remove all attributes for which the value is an empty string.
// Hierarchy Clean up functions
// Todo with this datastructure
// - How do I remove all fields with value of ""
// - For each object in the tree, change the object's key into its 'Name' attribute
function cleanHierarchyUp(obj) {
// obj is an array of objects, with or without a 'children' object (array of objects again)
// Goal: the object name should be its '.Name' name attribute if it exists
// Goal: if possible: all 'keys' for which the value is an empty string should be removed.
obj.forEach(function(element, index) {
// console.log(element)
if (element.Children) {
obj[element.Name] = cleanHierarchyUp(element)
} else {
obj[element.Name] = element
}
})
return obj
}
Help or direction is greatly appreciated.