This is a good candidate for Array.prototype.reduce().
props.reduce((acc, prop) => acc?.[prop], obj)
The .reduce() method iterates over each element in the array that it is called on and passes both the current element and the value that the previous invocation resolved to, to the next iteration.
It is basically equivalent to
let acc = obj;
for (let prop of props) {
acc = acc[prop];
}
return acc;
I also added the optional chaining operator (?.) so that when the element can't be found, it returns undefined instead of throwing an error.
const obj = {
category: {
category_name: "some name",
}
};
const props = ["category", "category_name"];
const props2 = ["does_not_exist", "category_name"];
console.log(props.reduce((acc, prop) => acc?.[prop], obj));
console.log(props2.reduce((acc, prop) => acc?.[prop], obj));
// Without optional chaining operator
console.log(props.reduce((acc, prop) => acc[prop], obj));
console.log(props2.reduce((acc, prop) => acc[prop], obj));