Skip to content

Instantly share code, notes, and snippets.

@gokulkrishh
Last active Mar 2, 2020
Embed
What would you like to do?
Useful javascript util functions

Useful javascript util functions

Table of contents

Flatten Object

function flattenObject(obj) {
  var output = {};

  for (var i in obj) {
    var v = obj[i];
    if (Array.isArray(v)) {
      output[i] = v.map(o => flattenObject(o));
    }
    else if (typeof v === "object") {
      temp = flattenObject(v)

      for (var k in temp) {
        output[i + '_' + k] = temp[k];
      }
    }
    else {
      output[i] = v;
    }
  }

  return output;
}

flatten({a: 1, b: { c: '2', d: [1, 2, { x: '1' }], f: { g: 'gokul' } }});

Result: {
  "a": 1,
  "b_c": "2",
  "b_d": [
    {},
    {},
    {
      "x": "1"
    }
  ],
  "b_f_g": "gokul"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment