MattV MattV - 4 years ago 148
JSON Question

Moving JSON values up in nested hierarchy until key is no longer named '_ignore'

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: {}
}


_root and _top2 should not be touched, but the top1 should have the lowest-level list as its value in the final structure. I'd like the object to look like this:

// 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: {}
}


I know I'm in the recursive domain, just haven't been able to apply it in a proper manner.
Help/direction is greatly appreciated.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download