# copyObject
# Description
将 source 的 props 属性 复制到 object 上,可根据 customizer 函数来处理数据,得到新的值
# Params
(source, props, object, customizer)
# Return
{Object} object
# Depend
import assignValue from './assignValue.js'
import baseAssignValue from './baseAssignValue.js'
# Code
function copyObject(source, props, object, customizer) {
const isNew = !object
object || (object = {})
for (const key of props) {
let newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined
if (newValue === undefined) {
newValue = source[key]
}
if (isNew) {
baseAssignValue(object, key, newValue)
} else {
assignValue(object, key, newValue)
}
}
return object
}
# Analyze
- 首先判断 是否传入
object定位一个标志isNew - 如果
object没有传入,将object设置为一个空对象 - 通过
for of拿到props中要赋值的key - 判断了是否传入了
customizer方法,如果传入了 则获取customizer方法返回的值,否则设置为undefined- 这里直接赋值为
undefined,略显不合理,因为customizer有可能直接返回undefined
- 这里直接赋值为
- 判断 如果
newValue为undefined,则将source中对应的值赋值给newValue - 根据 is
New 判断是否为一个全新的对象,如果是 则使用baseAssignValue进行赋值,否则使用assignValue`- 在这里用
isNew来区别是否全新对象,是因为性能问题,baseAssignValue并不会进行是否存在当前key的判断
- 在这里用
- 返回
object
# Remark
# Example
const a = {a:1,b:2,c:3}
const b = null
const c = {a:4,b:5,c:6,d:7}
copyObject(a, ['a','b'], b) // { a: 1, b: 2 }
copyObject(a, ['a','b'], b, (a,b)=>{return ++b}) // { a: 2, b: 3 }
copyObject(a, ['a','b'], c) // { a: 1, b: 2, c: 6, d: 7 }
← copyArray copySymbols →