Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

72
Views
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. 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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!