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

130
Views
JavaScript spread operator: deep attribute is changing after cloning the object

I am getting output is 5 but I was assuming 3. what is the logic behind and how can I make output 3.

const obj = {
  a: 1,
  b: 2,
  c: {
    p: 3
  }
}
const obj1 = { ...obj}
obj.c.p = 5

console.log(obj1.c.p)

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

0

The above only clones the first level, so changing obj's deep attribute will change the reference in obj1

const obj = {
  a: 1,
  b: 2,
  c: { p: 3 }
};

const obj1 = { ...obj, c: {...obj.c} };
obj.c.p = 5;

console.log(obj1.c.p);

about 4 years ago · Juan Pablo Isaza Report

0

obj spreaded to obj1 but object in c property stays same, e.g. c is a same object. Can deeply clone object like this

const obj1 = JSON.parse(JSON.stringify(obj))
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!