Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to clone an array which is nested inside another array in an object

I have an obj that looks like this.

let obj= {
  title:"my form",
  endTIme:"2/20/22",
  mainList:[
    {
      type:"multiple", 
      checked:false,
      multiple:[
         {
           optionCheck: false,
           optionAnswer:""
         }
      ]
    }
  ]
}

I also have a button that every time I click, I want the obj fields to retain all its values only that the multiple array field should append a new object . But I cant seem to figure it out. Please I really need help

I tried cloning using spread operator and I wasn’t getting the result I want as I learnt that spread operator is best used for shallow cloning

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let newObj= {
 ...obj
  mainList:[
     ...obj.mainList,
    {
      multiple:[
         {
           optionCheck: false,
           optionAnswer:""
         }
      ]
    }
  ]
}

And this ends up duplicating the mainList instead.

What I want my result to like is this when I click the button once.

let obj = {
  title: "my form",
  endTIme: "2/20/22",
  mainList: [{
    type: "multiple",
    checked: false,
    multiple: [
    {
      optionCheck: false,
      optionAnswer: ""
    }, 
    {
      optionCheck: false,
      optionAnswer: ""
    }]
  }]
};

>Solution :

Just use array.push

let obj= {
  title:"my form",
  endTIme:"2/20/22",
  mainList:[
    {
      type:"multiple", 
      checked:false,
      multiple:[
         {
           optionCheck: false,
           optionAnswer:""
         }
      ]
    }
  ]
}

obj.mainList[0].multiple.push( {
           optionCheck: false,
           optionAnswer:""
         });
         
console.log(obj)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading