_.updateWith(object, path, updater, [customizer])

该函数在对象中根据指定路径,使用提供的更新函数对属性进行更新,并使用自定义函数对属性进行处理。

参数

  • object:要更新属性的对象。
  • path:属性路径。
  • updater:更新函数,用于修改属性的值。
  • [customizer]:(可选)自定义函数,用于对属性进行处理。

返回值

返回更新后的对象。

示例

const object = {
  a: {
    b: {
      c: 1,
    },
  },
};

const result = _.updateWith(
  object,
  "a.b.c",
  (value) => value * 2,
  (newValue, key, obj, stack) => {
    if (key === "c") {
      return newValue + 10;
    }
  }
);

console.log(result);
// 输出: { a: { b: { c: 12 } } }

在上述示例中,我们有一个对象 object,其中包含嵌套的属性 a.b.c。使用 _.updateWith() 函数根据指定路径,使用提供的更新函数对属性进行更新,并使用自定义函数对属性进行处理。

在更新函数中,我们将属性值乘以 2。在自定义函数中,当属性键为 'c' 时,我们将新的属性值加上 10

通过调用 _.updateWith(object, 'a.b.c', ...),属性 a.b.c 的值被更新为 12