UNPKG

2.11 kBJavaScriptView Raw
1import {merge, sum} from "d3-array";
2import {keys} from "d3-collection";
3
4/**
5 @function merge
6 @desc Combines an Array of Objects together and returns a new Object.
7 @param {Array} objects The Array of objects to be merged together.
8 @param {Object} aggs An object containing specific aggregation methods (functions) for each key type. By default, numbers are summed and strings are returned as an array of unique values.
9 @example <caption>this</caption>
10merge([
11 {id: "foo", group: "A", value: 10, links: [1, 2]},
12 {id: "bar", group: "A", value: 20, links: [1, 3]}
13]);
14 @example <caption>returns this</caption>
15{id: ["bar", "foo"], group: "A", value: 30, links: [1, 2, 3]}
16*/
17function objectMerge(objects, aggs) {
18 if ( aggs === void 0 ) aggs = {};
19
20
21 var availableKeys = new Set(merge(objects.map(function (o) { return keys(o); }))),
22 newObject = {};
23
24 availableKeys.forEach(function (k) {
25 var values = objects.map(function (o) { return o[k]; });
26 var value;
27 if (aggs[k]) { value = aggs[k](values); }
28 else {
29 var types = values.map(function (v) { return v || v === false ? v.constructor : v; }).filter(function (v) { return v !== void 0; });
30 if (!types.length) { value = undefined; }
31 else if (types.indexOf(Array) >= 0) {
32 value = merge(values.map(function (v) { return v instanceof Array ? v : [v]; }));
33 value = Array.from(new Set(value));
34 if (value.length === 1) { value = value[0]; }
35 }
36 else if (types.indexOf(String) >= 0) {
37 value = Array.from(new Set(values));
38 if (value.length === 1) { value = value[0]; }
39 }
40 else if (types.indexOf(Number) >= 0) { value = sum(values); }
41 else if (types.indexOf(Object) >= 0) { value = objectMerge(values.filter(function (v) { return v; })); }
42 else {
43 value = Array.from(new Set(values.filter(function (v) { return v !== void 0; })));
44 if (value.length === 1) { value = value[0]; }
45 }
46 }
47 newObject[k] = value;
48 });
49
50 return newObject;
51
52}
53
54export default objectMerge;
55
56//# sourceMappingURL=merge.js.map
\No newline at end of file