How to use the mergeWith function from lodash

Find comprehensive JavaScript lodash.mergeWith code examples handpicked from public code repositorys.

lodash.mergeWith is a function that merges two or more objects or arrays recursively, and allows the customization of the merging process with a customizer function.

259
260
261
262
263
264
265
266
267
268
module.exports.maxBy               = _.maxBy;
module.exports.mean                = _.mean;
module.exports.meanBy              = _.meanBy;
module.exports.memoize             = _.memoize;
module.exports.merge               = _.merge;
module.exports.mergeWith           = _.mergeWith;
module.exports.method              = _.method;
module.exports.methodOf            = _.methodOf;
module.exports.methodize           = _.methodize;
module.exports.min                 = _.min;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

143
144
145
146
147
148
149
150
151
152
153
/*
 * Uses _.mergeWith to concat arrays, this helps replicate how Docker Compose
 * merges its things
 *
 */
exports.merge = (old, ...fresh) => _.mergeWith(old, ...fresh, (s, f) => {
  if (_.isArray(s)) return _.uniq(s.concat(f));
});


/*
fork icon35
star icon29
watch icon4

+ 5 other calls in file

How does lodash.mergeWith work?

lodash.mergeWith is a function that merges two or more objects deeply into one object with custom function as a resolver to determine how to merge values at each key. The custom function is called with four arguments: the destination value, the source value, the key, and the merged object.

179
180
181
182
183
184
185
186
187
188
        ignoreOrder: true,
        filename: '[name].css',
      }),
    ],
  };
  return mergeWith(defaults, config, mergeArrays);
};


module.exports = configs.map((config, index) => createWebpackConfig(config, { includeDevServer: index === 1 }));
fork icon25
star icon40
watch icon9

686
687
688
689
690
691
692
693
694
695
696
697
698
console.log(mapValues); // => { 'a': 'a1', 'b': 'b2' }


const merge = _.merge({ 'a': [{ 'b': 1 }, { 'd': 2 }] }, { 'a': [{ 'c': 3 }, { 'e': 4 }] });
console.log(merge); // => { 'a': [{ 'b': 1, 'c': 3 }, { 'd': 2, 'e': 4 }] }


const mergeWith = _.mergeWith({ 'a': [{ 'b': 1 }, { 'd': 2 }] }, { 'a': [{ 'c': 3 }, { 'e': 4 }] }, (a, b) => a + b);
console.log(mergeWith); // => { 'a': [{ 'b': 1, 'c': 3 }, { 'd': 2, 'e': 4 }] }


const omit = _.omit({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']);
console.log(omit); // => { 'b': '2' }
fork icon0
star icon4
watch icon0

+ 15 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const _ = require("lodash");

const customizer = (objValue, srcValue) => {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
};

const objA = { a: [1], b: [2], c: { x: 3 } };
const objB = { a: [4], b: [5], c: { y: 6 } };

const merged = _.mergeWith(objA, objB, customizer);

console.log(merged);
// Output: { a: [1, 4], b: [2, 5], c: { x: 3, y: 6 } }

In this example, we're merging two objects objA and objB into a new object called merged using lodash.mergeWith. We're also passing in a custom customizer function that specifies how to merge array values. The customizer function is called for each value being merged. If the value is an array, it will concatenate the source array (srcValue) onto the original array (objValue). If it's not an array, the value from the source object (srcValue) will overwrite the value in the original object (objValue). The resulting merged object has the same structure as the original objects, with arrays concatenated and values from objB overwriting values from objA.

281
282
283
284
285
286
287
288
289
290
  const {
    chunksById: { js, css }
  } = assets;

  const bundleBase = utils.getBundleBase(routeOptions);
  const allChunks = _.mergeWith({}, js, css, (a, b) => (a && b ? [].concat(a, b) : a || b));
  CDN_JS_BUNDLES = utils.mapCdnAssets(allChunks, bundleBase, CDN_ASSETS);

  return CDN_JS_BUNDLES;
},
fork icon309
star icon0
watch icon49

0
1
2
3
4
5
6
7
8
9
10
const ds = require('./datastore').client()
const appConfig = require('../../config')
const _ = require('lodash')


const mergeNonEmpty = (a, b) => {
  return _.mergeWith(a, b, (original, newValue) => {
    if (_.isUndefined(newValue) || _.isNull(newValue) || _.isNaN(newValue)) {
      return original
    }
    return undefined
fork icon3
star icon3
watch icon3

+ 10 other calls in file

107
108
109
110
111
112
113
114
115
116
117
    res.statusCode = 500;
    res.end('Internal Momo Error (×﹏×)');
  }
});


const config = _.mergeWith(
  {},
  defaultConfig,
  nextConfigs(undefined, { defaultConfig: {} }),
  (objValue, srcValue) => {
fork icon51
star icon738
watch icon47

+ 33 other calls in file

1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
.then(_document => {
	if (!_document) {
		return res.status(404).send();
	}
	oldValues = _document.toObject();
	updated = _.mergeWith(_document, body, customizer);
	if (body.attributes)
		updated.attributes = body.attributes;
	if (_.isEqual(JSON.parse(JSON.stringify(updated)), JSON.parse(JSON.stringify(oldValues)))) return;
	updated = new crudder.model(updated);
fork icon3
star icon0
watch icon4

1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
  }
].forEach(t => {
  describe(`${t.name}`, () => {
    let testRawData;
    beforeEach(async () => {
      testRawData = _.mergeWith(rawData, t.rawData);

      step = require('../determine-action');

      result = await step.execute(loggerMock, testRawData);
fork icon0
star icon1
watch icon1

+ 8 other calls in file

19
20
21
22
23
24
25
26
27
28
    }),
  ],
  stats: mode === 'development' ? 'minimal' : undefined,
};

return _.mergeWith(config, newConfig, (objValue, srcValue) => {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
});
fork icon0
star icon0
watch icon1

+ 2 other calls in file

8
9
10
11
12
13
14
15
16
17
18
};


if (strapi.EE) {
  const eeAdmin = require('./ee/strapi-server');


  module.exports = _.mergeWith({}, admin, eeAdmin, mergeRoutes);
} else {
  module.exports = admin;
}
fork icon0
star icon0
watch icon1

+ 17 other calls in file

333
334
335
336
337
338
339
340
341
342
  this.crossOriginAttribute = true
  this.browserSocketTimeout = 20000
}

set (newConfig) {
  _.mergeWith(this, newConfig, (obj, src) => {
    // Overwrite arrays to keep consistent with #283
    if (Array.isArray(src)) {
      return src
    }
fork icon0
star icon0
watch icon1

+ 3 other calls in file

28
29
30
31
32
33
34
35
36
37
    'app',
    process.env.ENABLE_MV3 ? 'manifest/v3' : 'manifest/v2',
    `${platform}.json`,
  ),
);
const result = mergeWith(
  cloneDeep(baseManifest),
  platformModifications,
  browserVersionMap[platform],
  await getBuildModifications(buildType, platform),
fork icon0
star icon0
watch icon1

+ 2 other calls in file

138
139
140
141
142
143
144
145
146
147
this.config = defaultConfig; // 配置参数
this.client = {}; // 阿里云OSS客户端
this.finalPrefix = ''; // 最终计算出来的prefix路径
this.currentProvider = {}; // 当前提供服务商信息
// 合并配置信息
this.config = lodash.mergeWith(lodash.cloneDeep(this.config), config || {}, function (objVal, srcVal) {
    if (lodash.isPlainObject(objVal) && lodash.isPlainObject(srcVal)) {
        return lodash.merge(objVal, srcVal);
    }
    return srcVal;
fork icon0
star icon0
watch icon1

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26


  return $.html();
};


const mergePurgeCSSOptions = (...options) =>
  mergeWith(...options, (objValue, srcValue) => {
    if (isArray(objValue)) {
      return objValue.concat(srcValue);
    }

fork icon0
star icon0
watch icon2

+ 3 other calls in file

198
199
200
201
202
203
204
205
206
207
208
/**
 * Add a graphql schema to the plugin's global graphl schema to be processed
 * @param {object} schema
 */
const addGraphqlSchema = (schema) => {
  _.mergeWith(strapi.config.get('plugin.i18n.schema.graphql'), schema, mergeCustomizer);
};


/**
 * Add localization mutation & filters to use with the graphql plugin
fork icon0
star icon0
watch icon0

29
30
31
32
33
34
35
      loadFiles(eeAdminPath, '!(config|test)/*.*(js|json)'),
      loadConfig(eeAdminPath),
    ]);
  }

  return _.mergeWith({}, files, eeFiles, config, eeConfig, mergeRoutes);
};
fork icon0
star icon0
watch icon1

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)