Javascript Object flatten

Description

Javascript Object flatten


function flattenObject(input) {
  if (!isObject(input)) {
    return -1;//from   www .j  a v a 2  s.c o  m
  }

  var output = {};
  flattenHelper(input, output, null);

  return output;
}

function flattenHelper(input, output, parentKey) {
  for (var key in input) {
    var flattenedKey = key;
    var val = input[key];

    if (parentKey !== null && parentKey.length > 0) {
      flattenedKey = parentKey + "." + key;
    }

    if (isObject(val)) {
      flattenHelper(val, output, flattenedKey);
    } else if (isArray(val)) {
      if (val.length > 0) {
        if (isObject(val[0]) || isArray(val[0])) {
          flattenHelper(val, output, flattenedKey);
        } else {
          output[flattenedKey] = val.toString();
        }
      }
    } else {
      output[flattenedKey] = val;
    }
  }
}

function isObject(d) {
  return typeof d === "object" && !Array.isArray(d);
}

function isArray(l) {
  return typeof l === "object" && Array.isArray(l);
}

var d = {
  "Key1": "1",
  "Key2": {
    "a" : "2",
    "b" : [{"x1": "3", "x2": "4"}, {"y1": "5", "y2": "6"}, {"z1": "7", "z2": "8"}],
    "c" : {
      "d" : "3",
      "e" : "1"
    }
  }
};

console.log(flattenObject(d));



PreviousNext

Related