Skip to content

Instantly share code, notes, and snippets.

@gokulkrishh
Last active March 2, 2020 05:17
Show Gist options
  • Save gokulkrishh/d249a15ddbd3a08f8d357f25965b41cd to your computer and use it in GitHub Desktop.
Save gokulkrishh/d249a15ddbd3a08f8d357f25965b41cd to your computer and use it in GitHub Desktop.
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