Skip to content

Instantly share code, notes, and snippets.

@dmitrythaler
Created July 4, 2016 19:30
Show Gist options
  • Save dmitrythaler/879d82befbae856600ee858b8a20d222 to your computer and use it in GitHub Desktop.
Save dmitrythaler/879d82befbae856600ee858b8a20d222 to your computer and use it in GitHub Desktop.
Combine objects
/**
* combine objects
*
* gets arrays with possible @param values, like
* [{a:1},{a:2}], [{b:'one'}, {b:'two'}], [{c:4,d:5},{c:7,d:9}]
* @returns all param values combinations
* [{ a: 1, b: 'one', c: 4, d: 5 },
* { a: 2, b: 'one', c: 4, d: 5 },
* { a: 1, b: 'two', c: 4, d: 5 },
* { a: 2, b: 'two', c: 4, d: 5 },
* { a: 1, b: 'one', c: 7, d: 9 },
* { a: 2, b: 'one', c: 7, d: 9 },
* { a: 1, b: 'two', c: 7, d: 9 },
* { a: 2, b: 'two', c: 7, d: 9 }]
*/
let combineObjects = function () {
let dst = [],
dst_len = 1,
alen = arguments.length, i, ai;
for (i = 0; i < alen; ++i) {
dst_len *= arguments[i].length;
}
for (i = 0; i < dst_len; ++i) {
let item = {},
idx = i;
for (ai = 0; ai < alen; ++ai) {
Object.assign( item, arguments[ai][idx % arguments[ai].length] );
idx = Math.floor( idx / arguments[ai].length );
}
dst.push( item );
}
return dst;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment