简体   繁体   English

JS - 洛达什; 嵌套对象(父/子)到平面阵列

[英]JS - Lodash; Nested Objects (parents/children) to flat array

I am using lodash (although solution doesn't have to) and I want to convert the following structure:我正在使用 lodash(尽管解决方案不是必须的)并且我想转换以下结构:

{ prop1: 'root',
  prop2: 'someVal',
  children: [
    { prop1: 'first Child',
      prop2: 'some other val',
      children: [
        { prop1: 'last child'
          prop2: 'another value'
          children: []
        }
      ]
    }
  ]
}

to a flat array:到平面阵列:

[ { prop1: 'root', prop2: 'someVal' }, 
  {prop1: 'firstChild', prop2: 'some Other Val'}, 
  {prop1: 'last child', prop2: 'another value'}
]

The depth can vary, and the last child will always have [] assigned to its children property;深度可以变化,最后一个孩子总是将[]分配给它的children属性; Note that in that particular case, the children array will always have a single item in it请注意,在这种特殊情况下,子数组中始终只有一个项目

Should be fairly straightforward but it seems I just can't put the finger on it for some reasons应该相当简单,但由于某些原因,我似乎无法解决它

Thanks谢谢

Solved with this snippet (in CoffeeScript)使用此代码段解决(在 CoffeeScript 中)

flatten = (node) ->
        row = node
        _.each node.children or [], (el) ->
            flatten el
        ancestors.push row

This is for using an anonymous target to flatten into (eg flattened )这是用于使用匿名目标展平(例如flattened

flatten = (collection, flattened = [])->
  _.each collection, (obj)->
    flattened.push obj
    flatten obj.children, flattened
  flattened

Solution using pure JS:- http://jsbin.com/bazilurolu/edit?js,console使用纯 JS 的解决方案:- http://jsbin.com/bazilurolu/edit?js,console

var flatArray = function(input){
    var result = [];
    (function(obj){
        var arr = [], newObj = {};
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if(key !== "children"){
                    newObj[key] = obj[key];
                }
                else{
                    arr = obj[key];
                }
            }
        }
        result.push(newObj);
        if(arr.length){
            arguments.callee(arr[0]);
        }
    })(input);
    return result;
};

Here is an Typescript version of the solution of @jusopi这是@jusopi 解决方案的打字稿版本

const flatten = (collection: any[], flattened?: any[]) => {
    if (!flattened) {
        flattened = [];
    }
    _.each(collection, (obj) => {
        flattened!.push(obj);
        flatten(obj.children, flattened);
    });
    return flattened;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM