Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save TGOlson/fc54667ccc0bb4b37bb8 to your computer and use it in GitHub Desktop.

Select an option

Save TGOlson/fc54667ccc0bb4b37bb8 to your computer and use it in GitHub Desktop.
Flatten JavaScript Objects
// delimter to join flattened keys
var delimiter = ' '
/*
* Flattens an object
* @param {object} object - object to flatten
* @param {boolean} shallow - if true object is only flattened one level
* @return {object} - flattened object
*/
function flatten(object, shallow) {
var flattened = {},
property,
value,
nextLevel,
prefix;
for(property in object) {
value = object[property];
if(typeof value === 'object' && shallow !== null && value !== null) {
// if shallow is required, set shallow to stopping keyword null
if(shallow) shallow = null;
nextLevel = flatten(value, shallow);
prefix = property + delimiter;
merge(flattened, nextLevel, prefix);
} else {
flattened[property] = value;
}
}
return flattened;
}
/*
* Destructively merges source data to an object
* @param {object} object - object to merge data into
* @param {object} source - object of source data
* @param {string} prefix - [optional] prefix properties with value
*/
function merge(object, source, prefix) {
var merged = {},
property,
value;
prefix = prefix || '';
for(property in source) {
value = source[property];
object[prefix + property] = value;
}
return object;
}
/*
* Examples
*/
// flatten an object with depth
var object = {1: {2: 3}};
flatten(object);
// => { '1 2': 3 }
// flatten a more complex object
var object = {
1: {
2: 3,
4: {5: 6},
7: {8: 9, 10: 11}
},
12: 13
};
flatten(object);
// => { '12': 13, '1 2': 3, '1 4 5': 6, '1 7 8': 9, '1 7 10': 11 }
// flatten an object with the shallow flag
var object = {
1: {
2: 3,
4: {5: 6},
7: {8: 9, 10: 11}
},
12: 13
};
flatten(object, true);
// => { '12': 13,
// '1 2': 3,
// '1 4': { '5': 6 },
// '1 7': { '8': 9, '10': 11 } }
// flatten an object with non-plain-object values
var object = {
1: {
2: null,
3: ['a', 'b', 'c'],
},
};
flatten(object);
// => { '1 2': null, '1 3 0': 'a', '1 3 1': 'b', '1 3 2': 'c' }
// note: arrays are flattened using their indices as property names
// this is the intended action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment