1

I'm dealing with certain difficulties finding a property deep in an object. Here are some scenarios:

{ redacted: true } vs { someProperty: true, anotherProperty: { redacted: true } }

I would like to be able to find redacted key in any object level. I tried to find some solutions inside libraries lodash but I didn't have any success.

Would be awesome to achieve something with this interface: findDeepProperty(obj, 'redacted')

Also, is there a way to achieve this algorithm by using an external library like lodash?

Laura Beatris
  • 1,782
  • 7
  • 29
  • 49
  • Conceptually, what's the point of getting a value if you don't know its context? Finding `obj.data.redacted` vs `obj.parent.redacted` may have very different implications. Practically, what's the expected result? Just the value? Or path and value? What if there are multiple matches? What result do you want there? – Thomas May 04 '21 at 22:34
  • Certain values are more complex, for instance: `{ salary: { amount: { redacted: true }, currency: "R$" } }` Doesn't matter the object level, the necessary logic is just to check for the existence of the `redacted` key It's not possible to have multiple matches - this is a design rule – Laura Beatris May 04 '21 at 23:25
  • But then you know exactly where the property should be. Just get it: `console.log(obj.salary.amount.redacted != undefined);` If this is about dealing with null-checks along the path, like let's say `salary` being `undefined`. Check out the [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). like `console.log(obj.salary?.amount.redacted != undefined);` – Thomas May 04 '21 at 23:41
  • @Thomas Not always that simple. I've had to use recursive depth search before myself – charlietfl May 04 '21 at 23:46

1 Answers1

0

First of all, it is really interesting problem. I managed to create a working solution in pure JavaScript, so you don't have to import any third-party libraries like lodash. It will try to find a property with given name as an input in the objects. It will use the algorithm from How to check the depth of an object? to go through the object in each depth. If it finds it, it will return the value of that propery. If it fails to find it, it will return an empty object. Here is the snippet:

let object = {
  'key1': {
    'key2': 'value2'
  },
  'key3': {
    'key4': {
      'key5': 'value5'
    },
  },
}

findDeepProperty = function(object, query_key) {
  for (let key in object) {
    if (key === query_key) {
      return object[key];
    }
    if (!object.hasOwnProperty(key)) continue;
    if (typeof object[key] == 'object') {
      let sub_result = findDeepProperty(object[key], query_key);
      if (Object.keys(sub_result).length) return sub_result;
    }
  }
  return {};
}

console.log(findDeepProperty(object, 'key3'))
NeNaD
  • 18,172
  • 8
  • 47
  • 89