gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:05:43 24 4
gpt4 key购买 nike

我正在使用 cloneDeepWith深度克隆一个 Object 并且在某些情况下,例如如果 keymodule,分配一个特定的 value,例如:

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 使用,但我在整个 Lodash 中找不到合适的 documentation .

最佳答案

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

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>

关于javascript - 如何使用定制器_cloneDeepWith_并添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com