JSFiddle - React, Tailwind, and code Playground

by Aaron Zhang

JavaScript

const isPlainObject = value => value?.constructor === Object;

function* flattern(current, prefix = "", delimiter = ".") {
  if (Array.isArray(current) || isPlainObject(current)) {
    for (const [key, value] of Object.entries(current)) {
      yield* flattern(value, prefix ? `${prefix}${delimiter}${key}` : key, delimiter);
    }
  } else {
    yield [prefix, String(current)];
  }
}

const flatternJSON = (obj, delimiter = ".") => Object.fromEntries(flattern(obj, "", delimiter));

console.log(flatternJSON({
  "isbn": "123-456-222",
  "author": {
    "lastname": "Doe",
    "firstname": "Jane"
  },
  "editor": {
    "lastname": "Smith",
    "firstname": "Jane"
  },
  "title": "The Ultimate Database Study Guide",
  "category": ["Non-Fiction", "Technology", {
    "somekey": "somevalue",
    "somelist": ["somelistvalu1", "somelistvalue2"],
  }],
}, delimiter="__"));