使用lodash深度压扁收集中的所有物品

nox*_*nox 1 javascript flatten underscore.js lodash flatmap

我想要展平一个看起来像这样的数组:

[{
    "id": 0,
    "text": "item 0"
}, {
    "id": 1,
    "items": [{
        "id": 2,
        "text": "item 2"
    }, {
        "id": 3,
        "items": [{
            "id": 4,
            "text": "item 4"
        }]
    }]
}]
Run Code Online (Sandbox Code Playgroud)

进入这个

[{
    "id": 0,
    "text": "item 0"
}, {
    "id": 2,
    "text": "item 2"
}, {
    "id": 4,
    "text": "item 4"
}]
Run Code Online (Sandbox Code Playgroud)

基本上保留所有没有"items"属性的元素,如果它们有一个,则以递归方式遍历所有"items"数组.

我确实可以写一个递归函数,但我正在寻找一个漂亮的lodash或下划线方法来解决这个问题.

Tho*_*lle 6

在lodash或下划线中没有这个功能.我认为递归函数是你最好的选择:

function collect(array, result) {
  array.forEach(function(el) {
    if(el.items) {
      collect(el.items, result);
    } else {
      result.push(el);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

var array = [{
    "id": 0,
    "text": "item 0"
}, {
    "id": 1,
    "items": [{
        "id": 2,
        "text": "item 2"
    }, {
        "id": 3,
        "items": [{
            "id": 4,
            "text": "item 4"
        }]
    }]
}];

function collect(array, result) {
  array.forEach(function(el) {
    if(el.items) {
      collect(el.items, result);
    } else {
      result.push(el);
    }
  });
}
var result = [];
collect(array, result);
console.log(result);
Run Code Online (Sandbox Code Playgroud)

  • 现在有`_.flatMapDeep()`递归地展平集合. (2认同)