Search code examples
javascriptjsonobjectcartesian-product

Flatten nested JSON to array of unique objects without indexes


I have this simple nested object which I need to flatten to be able to insert it into my database.

const input = {
  name: "Benny",
  department: {
    section: "Technical",
    branch: {
      timezone: "UTC",
    },
  },
  company: [
    {
      name: "SAP",
      customers: ["Ford-1", "Nestle-1"],
    },
    {
      name: "SAP",
      customers: ["Ford-2", "Nestle-2"],
    },
  ],
};

The desired result is like this, each value in the arrays results in a new sub-object stored in an array:

[
  {
    name: "Benny",
    "department.section": "Technical",
    "department.branch.timezone": "UTC",
    "company.name": "SAP",
    "company.customers": "Ford-1",
  },
  {
    name: "Benny",
    "department.section": "Technical",
    "department.branch.timezone": "UTC",
    "company.name": "SAP",
    "company.customers": "Nestle-1",
  },
  {
    name: "Benny",
    "department.section": "Technical",
    "department.branch.timezone": "UTC",
    "company.name": "SAP",
    "company.customers": "Ford-2",
  },
  {
    name: "Benny",
    "department.section": "Technical",
    "department.branch.timezone": "UTC",
    "company.name": "SAP",
    "company.customers": "Nestle-2",
  },
]

Instead of the result below which all fields stored in single object with indexes:

{
  name: 'Benny',
  'department.section': 'Technical',
  'department.branch.timezone': 'UTC',
  'company.0.name': 'SAP',
  'company.0.customers.0': 'Ford-1',
  'company.0.customers.1': 'Nestle-1',
  'company.1.name': 'SAP',
  'company.1.customers.0': 'Ford-2',
  'company.1.customers.1': 'Nestle-2'
}

My code looks like this:

function flatten(obj) {
  let keys = {};
  for (let i in obj) {
    if (!obj.hasOwnProperty(i)) continue;
    if (typeof obj[i] == "object") {
      let flatObj = flatten(obj[i]);
      for (let j in flatObj) {
        if (!flatObj.hasOwnProperty(j)) continue;
        keys[i + "." + j] = flatObj[j];
      }
    } else {
      keys[i] = obj[i];
    }
  }
  return keys;
}

Thanks in advance!


Solution

  • You could take the array's values as part of a cartesian product and get finally flat objects.

    const
        getArray = v => Array.isArray(v) ? v : [v],
        isObject = v => v && typeof v === 'object',
        getCartesian = object => Object.entries(object).reduce((r, [k, v]) => r.flatMap(s =>
            getArray(v).flatMap(w =>
                (isObject(w) ? getCartesian(w) : [w]).map(x => ({ ...s, [k]: x }))
            )
        ), [{}]),
        getFlat = o => Object.entries(o).flatMap(([k, v]) => isObject(v)
            ? getFlat(v).map(([l, v]) => [`${k}.${l}`, v])
            : [[k, v]]
        ),
        input = { name: "Benny", department: { section: "Technical", branch: { timezone: "UTC" } }, company: [{ name: "SAP", customers: ["Ford-1", "Nestle-1"] }, { name: "SAP", customers: ["Ford-2", "Nestle-2"] }] },
        result = getCartesian(input).map(o => Object.fromEntries(getFlat(o)));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }