I have an example object:
const obj = {
group: {
data: {
data: [
{
id: null,
value: 'someValue',
data: 'someData'
}
]
}
}
};
My objective is to retrieve a value by property name.
In this case, I am trying to get the value of the data
property, specifically the last occurrence of it.
Therefore, the expected output should be:
someData
However, I am using a recursive function to achieve this:
const findVal = (obj, propertyToExtract) => {
if (obj && obj[propertyToExtract]) return obj[propertyToExtract];
for (let key in obj) {
if (typeof obj[key] === 'object') {
const value = findVal(obj[key], propertyToExtract);
if (value) return value;
}
}
return false;
};
The current function returns the value of the first occurrence of data
, like so:
data: [
{
value: 'someValue',
data: 'someData'
}
]
What can be done to obtain the desired result?