當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。