Flatten hierarchical data

2019-01-26 22:09发布

问题:

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);

回答1:

It's easier to use plain js, like this

function flatten (data) {
  var result = [];

  while (data) {
    result.push({name: data.name, config: data.config});
    data = data.prev;
  }

  return result;
}

// get full object
 flatten(data)

// get only names
var res = flatten(data).map(function (el) {
  return el.name;
});

Example



回答2:

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>