Last Updated: October 17, 2017
·
11.53K
· mtimofiiv

Recursive merge/flatten objects in plain old vanilla Javascript

It's actually quite easy to do.

Give this function an array of objects and it will merge them into one.

var merge = function(objects) {
  var out = {};

  for (var i = 0; i < objects.length; i++) {
    for (var p in objects[i]) {
      out[p] = objects[i][p];
    }
  }

  return out;
}

Give this function a nested object and it will make it single-level

var flatten = function(obj, name, stem) {
  var out = {};
  var newStem = (typeof stem !== 'undefined' && stem !== '') ? stem + '_' + name : name;

  if (typeof obj !== 'object') {
    out[newStem] = obj;
    return out;
  }

  for (var p in obj) {
    var prop = flatten(obj[p], p, newStem);
    out = merge([out, prop]);
  }

  return out;
};

To use, simply:

var myObject = {
  name: 'fiiv',
  birthYear: 1986,
  favoriteColors: [ 'red', 'orange' ],
  isWearing: {
    shirt: {
      color: 'white'
    },
    shorts: {
      color: 'blue'
    }
  }
};

console.log(flatten(myObject));

And this produces:

{
  name: 'fiiv',
  birthYear: 1986,
  favoriteColors_0: 'red',
  favoriteColors_1: 'orange',
  isWearing_shirt_color: 'white',
  isWearing_shorts_color: 'blue'
}