合并对象的方法

一、ES6中的Object.assign()

Object.assign() 方法将所有可枚举的自有属性(对象自身的属性,不是原型属性)从一个或多个源对象复制到目标对象,返回合并后的对象。注意:该合并对象的方法是对对象里面属性的浅拷贝;并且会改变目标对象(第一个参数)。

const target = {}
const source1 = {b: 'yes'}
Object.defineProperties(target, {
	count: {
		value: "yes",
		enumerable: true // 可以被枚举
	},
	a: {
		value: "no",
		enumerable: false // 不可被枚举
	}
})
console.log(Object.assign(target, source1)) // { count: 'yes', b: 'yes', c: { foo: 'yes' } }
target.c.foo = "change"
console.log(source1) // { b: 'yes', c: { foo: 'change' } }

二、ES6中扩展运算符 ...

注意:也是对对象中属性的浅拷贝

let obj1 = {a: 0, o: {count: 0}};
let obj2 = {b: 2}
let combineObj = {...obj1, ...obj2}
combineObj.o.count = 11;
console.log(combineObj) // { a: 0, o: { count: 11 } ], b: 2 }
console.log(obj1) // { a: 0, o: { count: 11 } }

三、for...in 循环自定义一个函数

函数功能:可以实现源对象的深拷贝,或者浅拷贝,返回合并后的对象

// 定义一个深拷贝函数,该函数接收一个数组或者对象作为一个参数(可以深拷贝数组和对象,方便复用)
function deepCopy(parameter) {
	// 1.判断该属性是否是数组形式,根据其类型创建变量
	let newValue = Array.isArray(parameter) ? [] : {};
	// 2.循环该对象或数组的属性值,并判断是否是引用类型
	for(let key in parameter) {
		// 3.是引用类型继续递归(逐层拷贝)得到其值后赋值给 newValue
		if(typeof parameter[key] === "object") {
			newValue[key] = deepCopy(parameter[key])
		}else {
			// 是基本类型的话直接赋值
			newValue[key] = parameter[key]
		}
	}
	// 4.返回拷贝后的对象
	return newValue;
}
// 定义合并对象的方法
function extend(selectDeepOrShallow, ...arguments) {
	// 1.创建合并后的对象
	let combineObj = {};
	// 2.拿到传入的每个对象,因为对象存储在 arguments 数组中,需要循环操作
	for(let i = 0; i < arguments.length; i++) {
		// 3.拿到每个对象中的属性值,并判断其类型,并且是否需要深拷贝
		for(let key in arguments[i]) {
			if(typeof arguments[i][key] === "object" && selectDeepOrShallow) combineObj[key] = deepCopy(arguments[i][key])
			else combineObj[key] = arguments[i][key]
		}
	}
	// 4.返回合并后的对象
	return combineObj;
}
let combineObj = extend(true, obj1, obj2)
combineObj.o.count = 2323;
combineObj.arr[0].foo = 'change'; // 验证是否是深或浅拷贝
console.log(combineObj)
// {
//   a: 0,
//   o: { count: 2323 },
//   arr: [ { foo: 'change' }, 0, 23, 5 ],
//   b: 2
// }
console.log(obj1)
// { a: 0, o: { count: 0 }, arr: [ { foo: 'foo' }, 0, 23, 5 ] }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值