[英]Value change in 1 object changes in all objects in array
I have an array of objects.我有一个对象数组。 Each object has a key quantity
and value
.每个对象都有一个键quantity
和value
。 I want to duplicate each object in the array based on its quantity.我想根据其数量复制数组中的每个对象。 Next, I want to manipulate only one of the duplicated object in the array.接下来,我只想操作数组中的一个重复对象。 But on manipulating value
of 1 object, value of all duplicated objects change.但是在操作 1 个对象的value
时,所有重复对象的值都会发生变化。 Here is my code:这是我的代码:
let arr = [
{ id: 1, quantity: 3, value: 10 },
{ id: 2, quantity: 1, value: 5 },
{ id: 2, quantity: 5, value: 5 },
];
const newArr = [];
for (const a of arr) {
if (a.quantity > 1) {
let quantity = a.quantity;
a.quantity = 1;
while (quantity--) {
newArr.push(a);
}
}
}
arr = newArr;
arr[0].value = 1;
When I changed the value of arr[0]
to 1
, value
field of arr[1]
and arr[2]
also changed to 1.当我将arr[0]
的值更改为1
时, arr[1]
和arr[2]
的value
字段也更改为 1。
I have tried copying the object using spread operator and JSON.parse(JSON.parse())
, but none has worked.我尝试使用扩展运算符和JSON.parse(JSON.parse())
复制对象,但没有一个有效。
Because newArr.push(a)
.因为newArr.push(a)
。 a
push to newArr
ref to element of arr
a
newArr
ref 推送到arr
的元素
You can edit same as :您可以编辑相同:
let arr = [ { id: 1, quantity: 3, value: 10 }, { id: 2, quantity: 1, value: 5 }, { id: 2, quantity: 5, value: 5 }, ] const newArr = [] for (const a of arr) { if (a.quantity > 1) { let quantity = a.quantity; a.quantity = 1; while (quantity--) { newArr.push({...a}) } } } arr = [...newArr] arr[0].value = 1 console.log(arr) // example for Memory Management let a = { id: 1, quantity: 3, value: 10 } let b = { id: 1, quantity: 3, value: 10 } let c = arr[0] let d = {...arr[0]} console.log(a === arr[0]) // false : different allocates memory for contain value console.log(a === b) // false : different allocates memory for contain value console.log(c === arr[0]) // true : refer to a memory console.log(d === arr[0]) // false : different allocates memory for contain value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.