JavaScript How can I use Lodash/JS to recursively filter nested objects? lodash recursive filter

I have an array with objects of unknown depth, like this

var objects = [{
    id: 1,
    name: 'foo'
}, {
    id: 2,
    name: 'bar',
    childs: [{
        id: 3,
        name: 'baz',
        childs: [{
            id: 4,
            name: 'foobar'
        }]
    }]
}];

I would like to be able to filter a specific child object by it's id.

Currently I am using this little lodash script (referred from this question) but it works only with objects not deeper than one level. So searching for id: 1 and id: 2 would work fine while searching for id: 3 or id: 4 would return undefined.

function deepFilter(obj, search) {
    return _(obj)
        .thru(function(coll) {
            return _.union(coll, _.map(coll, 'children'));
        })
        .flatten()
        .find(search);
}

A little JSfiddle.

Answer:1

You could take an iterative and recursive approach.

function find(id, array) {
    var result;
    array.some(o => o.id === id && (result = o) || (result = find(id, o.children || [])));
    return result;
}

var objects = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar', children: [{ id: 3, name: 'baz', children: [{ id: 4, name: 'foobar' }] }] }];

console.log(find(1, objects));
console.log(find(2, objects));
console.log(find(3, objects));
console.log(find(4, objects));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer:2

You need to call the function recursively in order to target child object. Try following

Iterate over the array and for each object check whether the id is found. If yes, break and return the result, else continue to search in the child (if exists).

Approach 1 : Traverses the tree branch by branch

Using this approach, first the code traverses for first element till the last child, then second element this last child and so on.

var objects = [{id: 1,name: 'foo'}, {id: 2,name: 'bar',childs: [{id: 3,name: 'baz',childs: [{id: 4,name: 'foobar'}]}]}];

function findObject(arr, id) {
  var result;
  for (let i = 0 ; i < arr.length; i++) {
    if(arr[i].id === id) {
      result = arr[i];
      break;
    }
    if(arr[i].childs) {
      result = findObject(arr[i].childs, id);
      if(result) break;
    }
  }
  return result;
}

console.log(findObject(objects, 4));
Answer:3

You can do that recursively like so:

function deepFind(arr, search) {
    for(var obj of arr) {
        if(search(obj)) {
            return obj;
        }
        if(obj.childs) {
            var deepResult = deepFind(obj.childs, search);
            if(deepResult) {
                return deepResult;
            }
        }
    }
    return null;
}

Then use it like so:

var result = deepFind(objects, function(obj) {
    return obj.id === myId;
});

Example:

function deepFind(arr, search) {
    for(var obj of arr) {
        if(search(obj)) {
            return obj;
        }
        if(obj.childs) {
            var deepResult = deepFind(obj.childs, search);
            if(deepResult) {
                return deepResult;
            }
        }
    }
    return null;
}

var objects = [{id: 1,name: 'foo'}, {id: 2,name: 'bar',childs: [{id: 3,name: 'baz',childs: [{id: 4,name: 'foobar'}]}]}];

console.log("ID 1:", deepFind(objects, obj => obj.id === 1));
console.log("ID 4:", deepFind(objects, obj => obj.id === 4));
console.log("ID 7:", deepFind(objects, obj => obj.id === 7));
Answer:4

I am a learner in java script currently I am going through the regular expression for validating the password field, I want my password field to contain characters and only one number in any place of ...

I am a learner in java script currently I am going through the regular expression for validating the password field, I want my password field to contain characters and only one number in any place of ...

  1. regular expression validation string
  2. regular expression validation in javascript
  3. regular expression validation c#
  4. regular expression validation in c# code behind
  5. regular expression validation in asp.net
  6. regular expression validation in php
  7. regular expression validation for email
  8. regular expression validation online
  9. regular expression validation in java
  10. regular expression validation in angular 8
  11. regular expression validation in jquery
  12. regular expression validation in react js
  13. regular expression validation for phone number
  14. regular expression validation in mvc model
  15. regular expression validation in mvc
  16. regular expression validation for name
  17. regular expression validation in codeigniter
  18. regular expression validation in laravel
  19. regular expression validation angular
  20. regular expression validation in python

Please have a look of the following code snippet, I have a method someFunc of the Javascript class someClass Inside the onclick handler of the btn variable inside the method definition, I want to ...

Please have a look of the following code snippet, I have a method someFunc of the Javascript class someClass Inside the onclick handler of the btn variable inside the method definition, I want to ...

  1. access this javascript
  2. access parent this javascript
  3. access outer this javascript
  4. access javascript variable in html
  5. access javascript variable in php
  6. access javascript object
  7. access javascript object by key
  8. access javascript array
  9. access javascript variable in c#
  10. access javascript variable in typescript
  11. access javascript variable in jsp
  12. access javascript function from another file
  13. access javascript variable inside ajax success
  14. access javascript variable in visualforce page
  15. access javascript object property
  16. access javascript variable in java
  17. access javascript object by index
  18. access javascript variable in css
  19. access javascript variable in django template
  20. access javascript variable in razor code

this is my html <div> <h1 class="main-header logic-head av-settings-head"></h1> <div class="col-xs-12 col-xs-12 col-lg-12 tabcontent" > <form class="form-horizontal ...

this is my html <div> <h1 class="main-header logic-head av-settings-head"></h1> <div class="col-xs-12 col-xs-12 col-lg-12 tabcontent" > <form class="form-horizontal ...

I have created a sample typeorm project using the typeorm cli which has ormconfig.json by default: { "type": "postgres", "host": "localhost", "port": 5432, "username": "postgres", "...

I have created a sample typeorm project using the typeorm cli which has ormconfig.json by default: { "type": "postgres", "host": "localhost", "port": 5432, "username": "postgres", "...