merge.js 916 B

123456789101112131415161718192021222324252627
  1. import { isObject, getMergeFn } from './util.js';
  2. const withDefaultOptions = (options) => {
  3. return {
  4. arrayMergeType: 'combine',
  5. arrayMerge: getMergeFn(options ? options.arrayMergeType : 'combine'),
  6. ...options,
  7. };
  8. };
  9. export const merge = (objects, options) => {
  10. const opts = withDefaultOptions(options);
  11. return objects.reduce((prev, curr) => {
  12. Object.keys(curr).forEach((key) => {
  13. if (Array.isArray(prev[key]) && Array.isArray(curr[key])) {
  14. if (opts && opts.arrayMerge) {
  15. prev[key] = opts.arrayMerge(prev[key], curr[key]);
  16. }
  17. }
  18. else if (isObject(prev[key]) && isObject(curr[key])) {
  19. prev[key] = merge([prev[key], curr[key]], opts);
  20. }
  21. else {
  22. prev[key] = curr[key];
  23. }
  24. });
  25. return prev;
  26. }, {});
  27. };