emplo yee
emplo yee

Reputation: 235

JavaScript : Get Path of a given key-value pair in a nested Object (or JSON)

Let's assume,I have a nested object, but it contains an unique key with an unique identifier as a value.

How do I get the path until I get the key-value pair by its path, e.g. by using lodash.

import _ from 'lodash';
    
_.get(object, path);

Upvotes: 2

Views: 1280

Answers (1)

emplo yee
emplo yee

Reputation: 235

So, because nobody knew an answer, I found my own solution:

function getPath(obj, givenKey, givenValue) {
    for(var key in obj) {                                   
        if(obj[key] && typeof obj[key] === "object") {      
            var result = getPath(obj[key], givenValue, givenKey);              
            if(result) {                                    
                result.unshift(key);                        
                return result;                             
            }
        } else if(obj[key] === givenValue && key === givenKey ) {                      
            return [key];                                   
        }
    }
}

Upvotes: 4

Related Questions