I have 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 child with given ID. How to achieve this using Underscore.js?
My current realisation 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;  
        }
     }
} 
                children keys from your top level objectswhich leads to
var res = _(data).chain().
    pluck('children').
    flatten().
    findWhere({id: 3}).
    value();
And a demo
var data = [
    {
        "name": "AAAA",
        "children": [
            {"name": "vvv", "id": 3},
            {"name": "vvv22", "id": 4}
        ]
    },
    {
        "name": "BBBB",
        "children": [
            {"name": "ggg", "id": 5},
            {"name": "ggggv22", "id": 6}
        ]
    }
];
var res = _(data).chain().
    pluck('children').
    flatten().
    findWhere({id: 3}).
    value();
    
console.log(res);
<script src="http://underscorejs.org/underscore-min.js"></script>
I got this function using underscore which will do your work.
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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With