展平分层数据 [英] Flatten hierarchical data

查看:124
本文介绍了展平分层数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据结构:

{
    name: 'test',
    config: { ... },
    prev: {
        name: 'test1.1',
        config: { ... },
        prev: {
            name: 'test1.1.1',
            config: { ... },
            prev: {
                name: 'test1.1.1.1',
                config: { ... },
                prev: undefined
            }
        }
    }
}

结构可以在'prev'对象中包含任意数量的递归但相同的结构。

The structure can contain any number of recursive but identical structures inside the 'prev' object.

我想提取'name'每个孩子的财产。如何使用下划线将其展平以产生如下结果集:

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

我目前的解决方案是这个(这不是最优的。我想用一个_.chain来产生这个):

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


推荐答案

使用普通的js更容易,像这样

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

示例

这篇关于展平分层数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆