Assignment between JS objects

In the process of writing code, we often encounter the situation of object assignment. This article records several ways of assigning values ​​between objects.

One: Assign values ​​to the same properties in the object

Object.keys gets the keys of all objects and then traverses the assignment

	obj = {
		age : 18,
		sex : '男'
	}
	obj1 = {
		age : '',
		sex : ''
	}
  Object.keys(obj1).forEach(key=>{obj1[key]=obj[key]})

Assignment through for loop

obj = {
		age : 18,
		sex : '男'
	}
	obj1 = {
		age : '',
		sex : ''
	}
	
for(let k in obj){
	this.obj[k] = obj1[k];
}

Shallow copy Object.assign

Note: If the properties of the two objects are different, the redundant properties of the source object will also be copied to the obj target object.

obj = {
		age : 18,
		sex : '男'
	}
	obj1 = {
		age : '',
		sex : ''
}

Object.assign(obj,obj1);

Destructuring assignment

Eliminate different attributes: Assume that targetObj has four attributes a, b, c, and d, and originObj has three attributes a, b, and c.

let {d, ...targetObj} = originObj

Guess you like

Origin blog.csdn.net/drunk2/article/details/127664582
Recommended