'Getting last appearance of a deeply nested value by specified property

I've got this object as example:

const obj = {
    group: {
        data: {
            data: [
                {
                    id: null,
                    value: 'someValue',
                    data: 'someData'
                }
            ]
        }
    }
};

My goal is to get a value by propery name.

In this case I would like to get the value of the data propery, but the last appearance of it.

Meaning the expected output is:

someData

However, I'm using this recursive function to retreive it:

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;
};

Which gives me the first appearance of data, meaning:

data: [
    {
       value: 'someValue',
       data: 'someData'
    }
]

How can I get the wanted result?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source