alex alex - 22 days ago 8
Javascript Question

Search recursively for value in object by property name

I'm building an utility function that should search for a property name and return its value once it is found. It should do this recursively:

// Function
util.findVal = (object, propName) => {
for (let key in object) {
if (key === propName) {
console.log(propName)
console.log(object[key])
return object[key]
} else {
util.findVal(object[key], propName)
}
}
}

// Input
object: {
photo: {
progress: 20
}
}

// Usage
util.findVal(object, 'progress')


However the console log goes forever and the browser crashes. What am I doing wrong?

EDIT:

This is how I'm calling the function:

// Input

item: {
photo: {
file: {},
progress: 20
}
}

this.findProgress(item)

methods: {
findProgress (item) {
return util.findVal(item, this.propName)
}
}

Answer

You could use Object.keys and iterate with Array#some.

function findVal(object, key) {
    var value;
    Object.keys(object).some(function(k) {
        if (k === key) {
            value = object[k];
            return true;
        }
        if (object[k] && typeof object[k] === 'object') {
            value = findVal(object[k], key);
            return value !== undefined;
        }
    });
    return value;
}

var object =  { photo: { progress: 20 }};
console.log(findVal(object, 'progress'));