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


Lodash _.assignWith()用法及代碼示例

lodash中Object的_.assignWith()方法與_.assign方法相似,唯一的區別是它接受為生成分配值而調用的定製程序。此外,如果此處使用的定製程序返回未定義,則該分配將由方法處理。

注意:

  • 可以使用五個自變量調用此處使用的定製器,即objValue,srcValue,鍵,對象和源。
  • 通過此方法可以更改此處使用的對象。

用法:

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

參數:此方法接受上述和以下所述的三個參數:

  • object:它是目標對象。
  • sources:它是對象的來源。
  • customizer:它是自定義分配值的函數。

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



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

範例1:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining a function customizer 
function customizer(objectVal, sourceVal) { 
  return _.isUndefined(objectVal) ? sourceVal:objectVal; 
} 
  
// Calling assignWith method with its parameter 
let obj = _.assignWith({ 'geeksforgeeks':13 },  
                       { 'GFG':4 }, customizer); 
  
// Displays output  
console.log(obj);

輸出:

{ geeksforgeeks:13, GFG:4 }

範例2:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining a function customizer 
function customizer(objectVal, sourceVal) { 
  return _.isUndefined(objectVal) ? sourceVal:objectVal; 
} 
  
// Defining a function Num1 
function Num1() { 
  this.i = 11; 
} 
  
// Defining a function Num2 
function Num2() { 
  this.j = 12; 
} 
   
// Defining prototype of above functions  
Num1.prototype.k = 13; 
Num2.prototype.l = 14; 
  
// Calling assignWith method with its parameter 
let obj = _.assignWith({ 'i':10 },  
          new Num1, new Num2,customizer); 
  
// Displays output  
console.log(obj);

輸出:

{ i:10, j:12 }

參考: https://lodash.com/docs/4.17.15#assignWith

相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Lodash _.assignWith() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。