I have a data structure like this:
{
name: 'test',
config: { ... },
prev: {
name: 'test1.1',
config: { ... },
prev: {
name: 'test1.1.1',
config: { ... },
prev: {
name: 'test1.1.1.1',
config: { ... },
prev: undefined
}
}
}
}
The structure can contain any number of recursive but identical structures inside the 'prev' object.
I want to extract the 'name' property of each child. How can I flatten this using underscore to produce a resultset like so:
['test', 'test1.1', 'test1.1.1', 'test1.1.1.1']
It would be even greater if the flattening process could return something like
[
{name: 'test', config: { ... }},
{name: 'test1.1', config: { ... }},
{name: 'test1.1.1', config: { ... }},
{name: 'test1.1.1.1', config: { ... }}
]
My current solution is this (which is not optimal. I would like to use one _.chain to produce this):
var _self = {
flatten: function (obj) {
var map = [];
return _self.flattenRecurse(obj, map);
},
flattenRecurse: function (obj, map) {
map.push({name: obj.name, config: obj.config});
if (obj.prev) {
_self.flattenRecurse(obj.prev, map);
}
}
}
var flattened = _self.flatten(data);