Reputation: 235
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
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