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

83
Views
How to push the values inside array object using spread in javascript

I was trying to change/update the data inside an array, but it gives me error, please see the below code,

let array = [{
  name: "lol",
  age: "15",
  address: {
    street: "ABC street",
    road: "123"
  }
}]
const onChange = (props, value) => {
  console.log({ ...array,
    [props]: value
  })
  // it works for name,age but not working for street or road
  // if i pass street as a props it should update street property alone
}
onChange("street", 10);
//its adding another node instead of updating the address.streat object

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

0

It's adding another node because you're using a spread operator on an array so it's converting that array into an object property by index. I have slightly updated the code. Hope it'll solve your problem.

let array = [{
  name: "lol",
  age: "15",
  address: {
    street: "ABC street",
    road: "123"
  }
}]
const onChange = (props, value) => {
  if(props==="street"||props==="road"){
    console.log({ ...array[0],
    address:{
        ...array[0].address,
        [props]: value
    }
  })
  }else {
    console.log({ ...array[0],
        [props]: 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!