Walk through object

JavaScript, Object, Recursion, Generator · Nov 15, 2021

Creates a generator, that walks through all the keys of a given object.

  • Use recursion.
  • Define a generator function, walk, that takes an object and an array of keys.
  • Use a for...of loop and Object.keys() to iterate over the keys of the object.
  • Use typeof to check if each value in the given object is itself an object.
  • If so, use the yield* expression to recursively delegate to the same generator function, walk, appending the current key to the array of keys. Otherwise, yield an array of keys representing the current path and the value of the given key.
  • Use the yield* expression to delegate to the walk generator function.
const walkThrough = function* (obj) {
  const walk = function* (x, previous = []) {
    for (let key of Object.keys(x)) {
      if (typeof x[key] === 'object') yield* walk(x[key], [...previous, key]);
      else yield [[...previous, key], x[key]];
    }
  };
  yield* walk(obj);
};
const obj = {
  a: 10,
  b: 20,
  c: {
    d: 10,
    e: 20,
    f: [30, 40]
  },
  g: [
    {
      h: 10,
      i: 20
    },
    {
      j: 30
    },
    40
  ]
};
[...walkThrough(obj)];
/*
[
  [['a'], 10],
  [['b'], 20],
  [['c', 'd'], 10],
  [['c', 'e'], 20],
  [['c', 'f', '0'], 30],
  [['c', 'f', '1'], 40],
  [['g', '0', 'h'], 10],
  [['g', '0', 'i'], 20],
  [['g', '1', 'j'], 30],
  [['g', '2'], 40]
]
*/

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript Generator Functions

    JavaScript generator functions are an advanced yet very powerful ES6 feature, which you can start using in your code right now.

    Collection · 17 snippets

  • Omit matching object keys

    Creates an object composed of the properties the given function returns falsy for.

    JavaScript, Object · Oct 21, 2020

  • Pick matching object keys

    Creates an object composed of the properties the given function returns truthy for.

    JavaScript, Object · Oct 22, 2020

  • Get nested value in object

    Gets the target value in a nested JSON object, based on the given key.

    JavaScript, Object · Oct 19, 2020