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


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

lodash中Object的_.assignInWith()方法与_.assignIn方法相似,唯一的区别是它接受为生成分配值而调用的定制程序。此外,如果此处使用的定制程序返回未定义,则分配将由方法处理。

注意:

  • 可以使用五个自变量调用此处使用的定制器,即objValue,srcValue,键,对象和源。
  • 通过此方法可以更改此处使用的对象。

用法:

_.assignInWith(object, sources, [customizer])

参数:此方法接受三个参数,如下所述:

  • object:它是目标对象。
  • sources:它是对象的来源。
  • customizer:它是自定义分配值的函数。

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



以下示例说明了JavaScript中的Lodash _.assignInWith()方法:

范例1:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining a function customizer 
function customizer(objectVal, sourceVal) { 
  return _.isUndefined(objectVal) ? sourceVal:objectVal; 
} 
  
// Calling assignInWith method with its parameter 
let obj = _.assignInWith({ 'gfg':1 }, { 'geek':3 }, customizer); 
  
// Displays output  
console.log(obj);

输出:

{ gfg:1, geek:3 }

范例2:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining a function customizer 
function customizer(objectVal, sourceVal) { 
  return _.isUndefined(objectVal) ? sourceVal:objectVal; 
} 
  
// Defining a function GfG 
function GfG() { 
  this.p = 7; 
} 
  
// Defining a function Portal 
function Portal() { 
  this.r = 9; 
} 
   
// Defining prototype of above functions  
GfG.prototype.q = 8; 
Portal.prototype.s = 10; 
  
// Calling assignInWith method with its parameter 
let obj = _.assignInWith({ 'p':6 },  
          new GfG, new Portal,customizer); 
  
// Displays output  
console.log(obj);

输出:

{ p:6, q:8, r:9, s:10 }

参考: https://lodash.com/docs/4.17.15#assignInWith

相关用法


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