ArticleZip > Search Recursively For Value In Object By Property Name

Search Recursively For Value In Object By Property Name

When working with complex data structures in your code, you may often find yourself needing to search for a specific value within an object while targeting a particular property name. This process, known as searching recursively for a value in an object by property name, can be efficiently achieved with proper technique and a clear understanding of how JavaScript objects work. In this article, we will guide you through the steps to perform this search effectively.

To start the search process, you need a recursive function that traverses the object and its nested properties. We will create a function called `searchValueByPropertyName` that takes three parameters: the object you want to search, the property name you are looking for, and the value you want to match.

Javascript

function searchValueByPropertyName(obj, propertyName, searchValue) {
    for (let key in obj) {
        if (key === propertyName && obj[key] === searchValue) {
            return obj[key];
        } else if (obj[key] && typeof obj[key] === 'object') {
            let result = searchValueByPropertyName(obj[key], propertyName, searchValue);
            if (result !== null) {
                return result;
            }
        }
    }
    return null;
}

In this function, we loop through the keys of the object. If the current key matches the property name and the corresponding value matches the search value, we return that value. If the value of the current key is another object, we recursively call the function on that nested object.

Let's test this function with a sample object to see it in action:

Javascript

const sampleObject = {
    name: "John",
    age: 30,
    address: {
        city: "New York",
        country: "USA"
    }
};

const result = searchValueByPropertyName(sampleObject, "city", "New York");
console.log(result); // Output: "New York"

In this example, we use the `sampleObject` and search for the property name "city" with the value "New York." The function successfully returns the value "New York" associated with the property name "city" from the nested object.

Remember that this function will only return the first occurrence of the value that matches the property name. If you expect multiple matches, you can modify the function to store or return all matching values.

By following this approach and utilizing recursion, you can efficiently search for a specific value in an object by property name, even when dealing with nested structures. This technique can streamline your code and make your search operations more organized and concise. Happy coding!