- 本文参加了由公众号@若川视野 发起的每周源码共读活动, 点击了解详情一起参与。
这是源码共读的第36期,链接:[juejin.cn/post/711878…]
本次源码:[剔除对象中的属性 ]
核心代码
function omit(obj, fields) {
// eslint-disable-next-line prefer-object-spread
const shallowCopy = Object.assign({}, obj);
for (let i = 0; i < fields.length; i += 1) {
const key = fields[i];
delete shallowCopy[key];
}
return shallowCopy;
}
export default omit;
这是个简单的函数omit,接收参数有操作原对象obj,以及需要删除的属性数组fields;Object.assign将传入的obj对象进行浅拷贝,创建出一个新对象,防止污染原对象;通过对fields循环遍历删除新建对象中对应属性;将新对象返回
Object.assign()
Object.assign(target, ...sources) 方法将所有可枚举(Object.propertyIsEnumerable() 返回 true)和自有(Object.hasOwnProperty() 返回 true)属性从一个或多个源对象复制到目标对象,返回修改后的对象。
深拷贝
function deepClone(data) {
if(Array.isArray(data)) {
let cloneObject =[];
data.forEach(item => {
if (Object.prototype.toString.call(item) == "[Object Object]" || Array.isArray(item)) {
ObjectData.push(deepClone(data[item]))
} else {
ObjectData.push(data[item])
}
})
return cloneObject
} else if (Object.prototype.toString.call(data) == "[Object Object]") {
let ObjectData = {}
Object.keys(data).forEach(item => {
if (Object.prototype.toString.call(data[item]) == "[Object Object]") {
ObjectData[item] = deepClone(data[item])
} else {
ObjectData[item] = data[item]
}
})
return ObjectData
} else {
return data
}
}
其他
对发包流程大概了解暂时还未尝试,对单元测也不是很懂,有待提升