Skip to content

Instantly share code, notes, and snippets.

@roppa

roppa/conform.js

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.