[英]javascript deep copy members from array of objects
I have a array of objects, looks like我有一个对象数组,看起来像
[
{Time: , //time stamp
psi: //pressure value at the time
},
... //other objects in the array the same
]
The array is named "data"该数组被命名为“数据”
if I slice part of the array, and pass them to find local max and min values, would the code below deep copy and return the local extremes?如果我对数组的一部分进行切片,并将它们传递给查找局部最大值和最小值,那么下面的代码是否会深度复制并返回局部极值? How to verify?
如何验证?
var extreme = findLocalExtreme(data.slice(0, 10)); //slice(0, 10) for example, shallow copy
function findLocalExtreme(slicedArr){
//error control skipped, the array could be empty or only 1 member
let tempMax = slicedArr[0]; //would the "=" deep copy the object or just shallow copy?
let tempMin = slicedArr[0];
let slicedArrLength = slicedArr.length;
for (let i = 1; i < slicedArrLength; i++){
if (slicedArr[i].psi > tempMax.psi){
tempMax = slicedArr[I]; //deep copy or shallow copy?
}
if (slicedArr[i].psi < tempMin.psi){
tempMin = slicedArr[i];
}
}
return {
Max: tempMax,
Min: tempMin //is the value assignment in returned class deep copy, or still shallow copy?
}
}
Any advise welcome.欢迎任何建议。
let tempMax = slicedArr[0]
will just do the shallow copy instead you can do let tempMax = {...slicedArr[0]}
since your object is only at level one this will do a deepcopy, if it is nested you can use loadash's cloneDeep to do a deepcopy. let tempMax = slicedArr[0]
只会做浅拷贝,而不是你可以做let tempMax = {...slicedArr[0]}
因为你的 object 只在一级,这将做一个深拷贝,如果它是嵌套的,你可以使用loadash 的 cloneDeep 做一个深拷贝。
Anywhere you are assiging a object to a variable it is a shallow copy在将 object 分配给变量的任何地方,它都是浅拷贝
You can use loadsh
cloneDeep
method to copy objects or array.您可以使用
loadsh
cloneDeep
方法来复制对象或数组。
import _ from 'loadsh';
let arr = [
{name: 'temp'}
{name: 'temp1}
]
let copyArr = _.cloneDeep(arr);
Deep Copy of a nested array of objects using JSON.parse(JSON.stringify(your_array_here))
使用
JSON.parse(JSON.stringify(your_array_here))
的对象嵌套数组的深层复制
reference link Deep Copy & Shallow Copy 参考链接 Deep Copy & Shallow Copy
//Deep Clone let a = [{ x:{z:1}, y: 2}]; let b = JSON.parse(JSON.stringify(a)); b[0].xz=0 console.log(a); console.log(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.