7

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

2 Answers 2

21
  1. Pluck the children keys from your top level objects
  2. Flatten the resulting array
  3. Find the first object matching the condition, e.g having the correct id
  4. Chain these operations

which 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>

Sign up to request clarification or add additional context in comments.

3 Comments

Am I right that this example will only go 2 levels deep? I am looking for an example that can handle variable levels deep...
That's right. For a variable depth, you probably would use a recursion. Feel free to ask a question if you can't find what you want
I'm trying to use this by matching against an outside variable in the findWhere statement but it would appear the variable is not available to the methods. How would I handle this? Thanks.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.