如何使用定制器_cloneDeepWith_并添加属性

How to _cloneDeepWith_ with customizer and add properties

我正在使用 cloneDeepWith 深度克隆一个 Object 并且在某些情况下,例如 key 模块 ,分配一个特定的喜欢:

const myObject = {
  foo: [1, 2, 3],
  bar: {
    module: 'lorem ipsum',
    test: 123
  },
  module: 'hello'
}

function customizer(val, key, obj) {
  if (key === 'module') {
    return 'custom'
  }
}

const clonedObject = _.cloneDeepWith(myObject, customizer)

console.log(clonedObject)
<script src="https://cdn.jsdelivr.net/lodash/4.14.0/lodash.min.js"></script>

问题

关键是现在我需要 添加 一些 属性 在满足条件的情况下。例如,如果迭代中的 obj 有一个 key === 'test',则添加一些属性。请参阅下面的代码:

const myCustomProps = { a: 'lorem', b: 'ipsum' }

function customizer(val, key, obj) {
  if (obj.hasOwnProperty('test')) {

    //---> Hoping could return the Object instead of value, like:
    return Object.assign({}, obj, {
      ...myCustomProps
    })
  }
}

const clonedObject = _.cloneDeepWith(myObject, customizer)

可能cloneDeepWith不合适function使用,但我在整个Lodashdocumentation中找不到合适的。

我认为您将不得不分别执行克隆和赋值。拥有克隆的对象后,您可以使用分配新道具的函数递归调用 _.forEach 。在此示例中,所有具有键 'test' 的对象都将添加新道具。

const myCustomProps = { a: 'lorem', b: 'ipsum' }

const clonedObject = {
  foo: [1, 2, { test: 123 }],
  bar: {
    module: 'custom',
    test: 123,
    baz: {
      test: 123,
    }
  },
  module: 'custom'
}

function iteratee(val) {
  // Base case
  if (!val || (typeof val !== 'object' && !Array.isArray(val))) {
    return
  }

  // Recursively apply iteratee 
  _.forEach(val, iteratee)

  // Perform check
  if (val.hasOwnProperty('test')) {
    Object.assign(val, {...myCustomProps})
  }
}

const result = _.forEach(clonedObject, iteratee)

console.log(clonedObject)
<script src="https://cdn.jsdelivr.net/lodash/4.14.0/lodash.min.js"></script>