Underscore.js Find and return an element in a nested array

I have a data structure like this:

[
    {
        "name": "AAAA",
        "children": [
            {"name": "vvv", "id": 3},
            {"name": "vvv22", "id": 4}
        ]
    },
    {
        "name": "BBBB",
        "children": [
            {"name": "ggg", "id": 5},
            {"name": "ggggv22", "id": 6}
        ]
    },
]

And I want to find and return the child with the given ID. How to do it with Underscore.js?

My current implementation without using Underscore:

for (var i = 0; i < data.length; i++) {
     var dataItem= data[i];
     for (var j = 0; j < dataItem.children.length; j++) {
        var child = dataItem.children[j];
        if (child .id == id) {
             return child;  
        }
     }
} 
+4
source share
2 answers

that leads to

var res = _(data).chain().
    pluck('children').
    flatten().
    findWhere({id: 3}).
    value();

And demo Go to Fiddle Button

+16
source

I got this feature using underscore that will do your job.

var getChild = function(id,data){
    var allChildren = _.flatten(_.pluck(data,'children'));
    var childWithId = _.find(allChildren,function(child){return child.id == id});
    return childWithId;
}

var child = getChild(5,data);
console.log(child);
+3
source

Source: https://habr.com/ru/post/1548478/


All Articles