当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Lodash _.mergeWith()用法及代码示例


Lodash是一个JavaScript库,可在underscore.js之上运行。 Lodash帮助处理数组,字符串,对象,数字等。

_.mergeWith()方法使用定制程序函数,该函数将被调用以生成给定目标和源属性的合并值。当定制程序函数返回undefined时,合并将由方法处理。它与_.merge()方法几乎相同。

用法:

_.mergeWith( object, sources, customizer )

参数:此方法接受上述和以下所述的三个参数:

  • object:此参数保存目标对象。
  • sources:此参数保存源对象。它是一个可选参数。
  • customizer:这是自定义分配值的函数。

返回值:此方法返回对象。



范例1:

Javascript

// Requiring the lodash library   
const _ = require("lodash");   
  
// The destination object 
var object = { 
  'amit':[{ 'susanta':20 }, { 'durgam':40 }] 
}; 
   
// The source object 
var other = { 
  'amit':[{ 'chinmoy':30 }, { 'kripamoy':50 }] 
}; 
  
// Using the _.mergeWith() method  
console.log(_.mergeWith(object, other));

输出:

{ ‘amit’:[{‘chinmoy’:30, ‘susanta’:20 }, { ‘durgam’:40, ‘kripamoy’:50 }] }

范例2:

Javascript

// Requiring the lodash library   
const _ = require("lodash");   
  
// Defining the customizer function 
function customizer(obj, src) { 
  if (_.isArray(obj)) { 
    return obj.concat(src); 
  } 
} 
   
// The destination object 
var object = { 
  'amit':[{ 'susanta':20 }, { 'durgam':40 }] 
}; 
   
// The source object 
var other = { 
  'amit':[{ 'chinmoy':30 }, { 'kripamoy':50 }] 
}; 
  
// Using the _.mergeWith() method  
console.log(_.mergeWith(object, other, customizer));

输出:

{ ‘amit’:[{‘susanta’:20 }, { ‘durgam’:40}, {‘chinmoy’:30}, {‘kripamoy’:50 } ]}

相关用法


注:本文由纯净天空筛选整理自sanjoy_62大神的英文原创作品 Lodash _.mergeWith() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。