Given an object as shown below, how would I approach moving all values up in the hierarchy until their parent no longer is named _ignore?
In an attempt to transform Excel CSV data to a nested json object, I ended up with something that looks like the following:
// Old structure:
var obj = {
_root: {},
_top1: {
"_ignore": {
"_ignore": [
"I can no longer traverse down",
"so the list that contains this",
"text should be placed under the",
"_top1 node, which is the first",
"parent not named _ignore. It should",
"be the only child to '_top1'."
]
}
},
_top2: {}
}
// Desired structure:
var obj = {
_root: {},
_top1: [
"I can no longer traverse down",
"so the list that contains this",
"text should be placed under the",
"_top1 node, which is the first",
"parent not named _ignore"
],
_top2: {}
}
Indeed you basically just want the contents of the deepest _ignore. Since you're also converting all ancestor objects (except for obj itself) to arrays, it's safe to say that any other properties can be destroyed. In other words, an object has either an _ignore property or is the actual content we're looking for.
In one sentence you could say; give me the contents of _ignore if is there, and recurse that.
In pseudo code:
function findContents (level) {
if (i have an ignored level)
return findContents (ignored level)
else
return level
}
In Javascript code:
const findContents = obj => obj._ignore
? findContents(obj._ignore)
: obj;
And to apply that to your structure:
obj._top1 = findContents(obj._top1);
Have fun