Home > Blockchain >  How to push the values inside array object using spread in javascript
How to push the values inside array object using spread in javascript

Time:12-04

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
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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
      })
  }
}

  • Related