Object.assign merges object deep copy and shallow copy issues

enum objects to merge

				const marker = {
    
    
					id: 1,
					iconPath: img,
					width: 50,
					height: 50,
					joinCluster: true, // 指定了该参数才会参与聚合
					label: {
    
    
						width: 50,
						height: 30,
						borderWidth: 1,
						borderRadius: 10,
						bgColor: '#ffffff'
					}
				};

				const positions = [{
    
    
					latitude: 35.040266,
					longitude: 118.351174,
				}, {
    
    
					latitude: 35.05151,
					longitude: 118.34787,
				}, {
    
    
					latitude: 35.042009,
					longitude: 118.356077,
				}, {
    
    
					latitude: 35.037898,
					longitude: 118.350418,
				}]

Implemented code

				const markers = []
				positions.forEach((p, i) => {
    
    
					const newMarker = Object.assign({
    
    }, marker, p)
					newMarker.id = i + 1
					newMarker.label.content = i + 1
					markers.push(newMarker)
				})

The return result of printing markers is different from expected. The same key value id is a deep copy and label.content is a shallow copy.
Insert image description here
Modify the code as

				const markers = []
				positions.forEach((p, i) => {
    
    
					const newMarker = Object.assign({
    
    }, marker, p)
					newMarker.id = i + 1
					newMarker.label.content = `label ${
      
      i + 1}`
					var newMarkers = JSON.parse(JSON.stringify(newMarker))
					markers.push(newMarkers)
				})

Just write it this way.
Summary: When Object.assign merges objects, the first layer is a deep copy and the second layer is a shallow copy. The shallow copy of newMarker.label.content can be understood as the referenced marker.label.content.
marker.label.content changes all The newMarker.label.content changes accordingly, so we get 4 contents: 4 Just make a deep copy of newMarker before pushing to save.

Guess you like

Origin blog.csdn.net/qq_47247479/article/details/126626406