-4

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
  • 979
  • 1
  • 9
  • 25

1 Answers1

2

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
  • 123,782
  • 12
  • 99
  • 138