Horje
How to Find Property by Name in a Deep Object Using Lodash?

When working with deeply nested objects in JavaScript, finding a specific property can be challenging. Using Lodash, a powerful utility library, simplifies this task with its robust set of functions. This guide explores how to effectively search for a property by name within a deeply nested object using Lodash, ensuring you can quickly and efficiently locate the data you need.

Prerequisites

Approach

In this approach, we look through a deeply nested object to find a specific property. for that we have used _.has() and _.isObject() methods. The findPropertyByName function takes the object and the property name to search for. It uses a helper function search to look at each level of the object. If the property is found, it stores the value in result. If not, it keeps looking through any nested objects. This method ensures you can find a property no matter how deeply it’s hidden in the object.

Install Lodash as a dependency:

npm install lodash

Dependencies:

"dependencies": {
"lodash": "^4.17.21"
}

Example: This example shows the implementation of the above-explained approach.

JavaScript
//src/index.js

const _ = require('lodash');

const deepObject = {
    level1: {
        level2: {
            level3: {
                target: 'found me!',
                anotherProperty: 'another value'
            },
            anotherLevel2Prop: {
                target: 'another target',
            }
        },
        level2Another: 'value'
    },
    level1Another: 'value'
};

const findPropertyByName = (obj, key) => {
    let result;
    const search = (obj) => {
        if (result !== undefined) return;
        if (_.has(obj, key)) {
            result = obj[key];
            return;
        }
        _.forOwn(obj, (value) => {
            if (_.isObject(value)) {
                search(value);
            }
        });
    };
    search(obj);
    return result;
};

const result = findPropertyByName(deepObject, 'target');
console.log(result);

Run the JavaScript code:

node src/index.js

Output:

found me!



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Import a Single Lodash Function? How to Import a Single Lodash Function?
How to Remove First and Last Element from Array using JavaScript? How to Remove First and Last Element from Array using JavaScript?
How to Sort an Array Based on the Length of Each Element in JavaScript? How to Sort an Array Based on the Length of Each Element in JavaScript?
Data Analysis with JavaScript? Data Analysis with JavaScript?
How to Convert Object Containing Objects into Array of Objects using Lodash? How to Convert Object Containing Objects into Array of Objects using Lodash?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18