Home > Blockchain >  Value change in 1 object changes in all objects in array
Value change in 1 object changes in all objects in array

Time:05-28

I have an array of objects. Each object has a key quantity and 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. 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.

I have tried copying the object using spread operator and JSON.parse(JSON.parse()), but none has worked.

CodePudding user response:

Because newArr.push(a) .a push to newArr ref to element of 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

  • Related