Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deep flatten all items in collection using lodash

I'm looking to flatten an array that look like this:

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

into this

[{
    "id": 0,
    "text": "item 0"
}, {
    "id": 2,
    "text": "item 2"
}, {
    "id": 4,
    "text": "item 4"
}]

basically keeping all element that doesn't have an "items" property, and if they have one, recursively traverse all "items" arrays deep.

I could indeed write a recursive function, but I'm looking for a nice looking lodash or underscore way to solve this.

like image 762
nox Avatar asked Sep 02 '16 17:09

nox


People also ask

How do you flatten objects in Lodash?

The Lodash. flatten() method is used to flatten the array to one level deep. Parameter: This method accepts single parameter array that holds simple array or array of arrays. Return Value: The return type of this function is array.

Is Deep equal Lodash?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.

Is Lodash merge deep?

merge() is a deep copy whereas _. assign() is a shallow copy.


1 Answers

There is no neat function for this in lodash or underscore. I think a recursive function is your best bet:

function collect(array, result) {
  array.forEach(function(el) {
    if(el.items) {
      collect(el.items, result);
    } else {
      result.push(el);
    }
  });
}

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);
like image 183
Tholle Avatar answered Sep 28 '22 07:09

Tholle