Flatten hierarchical data
Recursive strategy
var data = {
name: 'test',
config: { },
prev: {
name: 'test1.1',
config: { },
prev: {
name: 'test1.1.1',
config: { },
prev: {
name: 'test1.1.1.1',
config: { },
prev: undefined
}
}
}
};
var reduced = flatten(data, function(item) {
return { name: item.name, config: item.config };
});
print(reduced.map(function(item) { return item.name }).join(', '));
function flatten(data, reducerFn, result) {
result = result || [];
if (data === undefined) return result;
return flatten(data.prev, reducerFn, result.concat([reducerFn(data)]));
}
/* For Display Purposes Only */function print(str) {
document.getElementById('display').innerHTML += str + '<br />';
}
<div id="display"></div>
It's easier to use plain js, like this
const data = {
name: 'test',
config: { },
prev: { name: 'test1.1',
config: { },
prev: {
name: 'test1.1.1',
config: { },
prev: { name: 'test1.1.1.1', config: { }, prev: undefined }
}
}
};
function flatten (data) {
let result = [];
while (data) {
result.push({ name: data.name, config: data.config });
data = data.prev;
}
return result;
}
console.log(flatten(data));
// get only names
const res = flatten(data).map(el => el.name);
console.log(res);