UNPKG

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