📜  Lodash _.assignInWith() 方法

📅  最后修改于: 2022-05-13 01:58:09.737000             🧑  作者: Mango

Lodash _.assignInWith() 方法

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

笔记:

  • 此处使用的定制器可以使用五个参数调用,即 objValue、srcValue、 keyobjectsource。
  • 此处使用的对象是通过此方法更改的。

句法:

_.assignInWith(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);


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);


输出:

{ 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