Skip to content

Instantly share code, notes, and snippets.

@titogeorge
Created November 24, 2017 13:03
Show Gist options
  • Save titogeorge/9549cca777a67ec0c84a25e65be9e616 to your computer and use it in GitHub Desktop.
Save titogeorge/9549cca777a67ec0c84a25e65be9e616 to your computer and use it in GitHub Desktop.
Flatten and given java script object.
function flatten(originalObject, newObj, keyNamePrefix) {
if (newObj == undefined) {
newObj = {};
}
if (typeof originalObject == 'object') {
for (key in originalObject) {
if (typeof originalObject[key] == 'object') {
let item = originalObject[key];
if (keyNamePrefix == undefined) {
flatten(item, newObj, key);
} else {
flatten(item, newObj, keyNamePrefix + "."+ key);
}
} else {
if (keyNamePrefix == undefined) {
newObj[key] = originalObject[key];
} else {
newObj[keyNamePrefix + '.' + key] = originalObject[key];
}
}
}
}
return newObj;
}
@titogeorge
Copy link
Author

Convert

{
  "a": "abc",
  "b": {
    "b1": "bcd",
    "b2": {
      "b21": "ccccc",
      "b22": "ccccc"
    }
  },
  "c": [
    {
      "c1": "cde"
    },
    {
      "c1": "def"
    }
  ]
}

to

{
  "a": "abc",
  "b.b1": "bcd",
  "b.b2.b21": "ccccc",
  "b.b2.b22": "ccccc",
  "c.0.c1": "cde",
  "c.1.c1": "def"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment