-3

I have a javascript plain object like this one: {a: {b: 1} } and I want to convert it to a dot-notation string like this a.b = 1

use case:

sending the object to a plain-text environment such as cli or as a url parameter.

Sh eldeeb
  • 1,589
  • 3
  • 18
  • 41
  • Why would you want to do that? – Take-Some-Bytes Sep 19 '21 at 20:22
  • You can iterate over a nested object and store the path: https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objects – jabaa Sep 19 '21 at 20:23
  • See [Recursively looping through an object to build a property list](https://stackoverflow.com/questions/15690706/recursively-looping-through-an-object-to-build-a-property-list) – ggorlen Aug 31 '23 at 01:41

1 Answers1

4

It's rather hard to tell whether this is what you want, but something like this would flatten a tree of objects into a list of dotted paths...

var data = {
  a: {
    b: 1,
    c: {
      d: 8
    }
  },
  e: {
    f: {
      g: 9
    },
    h: 10,
    i: [1, 2, 3]
  }
};


function toDotList(obj) {
  function walk(into, obj, prefix = []) {
    Object.entries(obj).forEach(([key, val]) => {
      if (typeof val === "object" && !Array.isArray(val)) walk(into, val, [...prefix, key]);
      else into[[...prefix, key].join(".")] = val;
    });
  }
  const out = {};
  walk(out, obj);
  return out;
}

console.log(toDotList(data));
AKX
  • 152,115
  • 15
  • 115
  • 172