M
M
mraser2020-03-20 14:40:54
JavaScript
mraser, 2020-03-20 14:40:54

How to get an array of keys by which you can get a known value from a nested object?

const obj = {'a': {'b': 1, 'c': 2, 'd': {...}, ...}, ....};

const keys = find(obj, 1); // ['a', 'b']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-03-20
@mraser

const findPath = (obj, val) =>
  Object.is(obj, val)
    ? []
    : Object.entries(obj instanceof Object ? obj : {}).reduce((found, n) => {
        if (!found) {
          found = findPath(n[1], val);
          if (found) {
            found.unshift(n[0]);
          }
        }

        return found;
      }, null);

A
Alexander, 2020-03-20
@Seasle

Are there any attempts to do so? Looks more like a mission.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question