Skip to content

Instantly share code, notes, and snippets.

@roppa
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roppa/11aec90488fef8d3bbff to your computer and use it in GitHub Desktop.
Save roppa/11aec90488fef8d3bbff to your computer and use it in GitHub Desktop.
Make all objects in an array have the same attributes
/**
Conform. We have a collection of objects with the possibility of having unique attributes.
We would like to ensure that each object in the collection has the same attributes. Handy for passing objects
to a CSV function that expects all objects to conform:
Example: var coll = [{a : "a", b : ""}, {a : "a", c : "c"}, {a : "a", d : "d", f : "f"}];
conform(coll);
@param array array of objects.
*/
function conform(collection) {
"use strict";
var keys = [], i = 0, j, cur;
if (Array.isArray(collection)) {
//loop through each object and get all of their keys, add them to keys if it isn't there already
for (i = 0; i < collection.length; i = i + 1) {
if (typeof collection[i] === "object") {
keys = keys.concat(Object.keys(collection[i]));
}
}
//now make sure that each object has all of the attributes in keys
for (i = 0; i < collection.length; i = i + 1) {
cur = collection[i];
for (j = 0; j < keys.length; j = j + 1) {
if (!cur.hasOwnProperty(keys[j])) {
cur[keys[j]] = null;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment