JS - Lodash;嵌套对象(父/子)到平面数组

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

本文关键字:数组 平面 Lodash 嵌套 对象 JS      更新时间:2023-09-26

我正在使用lodash(尽管解决方案不需要),我想转换以下结构:

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

转换为平面数组:

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

深度可以改变,最后一个子节点总是将[]赋给它的children属性;注意,在这种特殊情况下,children数组中总是只有一个元素

应该是相当直接的,但似乎我就是不能把手指放在它的一些原因

谢谢

解决了这个代码段(在CoffeeScript中)

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

这是用于使用匿名目标扁平化为(例如flattened)

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

使用纯JS解决方案http://jsbin.com/bazilurolu/edit?js,控制台

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

下面是@jusopi解决方案的Typescript版本

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