Home > Software design >  Why doesn't the spread operator add properties to my array?
Why doesn't the spread operator add properties to my array?

Time:07-14

I'm working with a React useState variable. I have an array of objects that has 18 objects at this top level. I'm trying to update the object at the 14th index and then return the remaining objects after it. At first I was directly mutating the state by pushing my changes to it like so:

 setFormWizard(wizard => {
    wizard.controls[14].trash = true;
    return ({
      ...wizard,
      wizard: wizard.controls[14].group.push(...newSection.slice(0, 5)),
    });
  });

This works, but I'm told this isn't good practice because React may not catch the update if you push directly to the state in certain cases. So now I'm trying to use the spread operator instead.

What's happening is the first 14 objects are returning. The object I'm modifying is returning, but the rest of the objects that come after the 14th index are not returning. What am I doing wrong?

setFormWizard(wizard => {
  const subjectControls = wizard.controls[14]
  const groups = [...controls.group, ...subjectAddressCopy.slice(0, 5)]
  return ({
    ...wizard,
    controls: [
      ...wizard.controls.splice(0,14), // keep first 14 entries 
      {
        ...subjectControls,
        group: groups,
        trash: true
      } // modify the 15th entry
        ...wizard.controls.splice(15) // this doesn't return the remaining controls
      ],
  });
});

CodePudding user response:

bcz splice changes in actual array you need to use slice

const arr = [1, 2, 3, 4]
arr.splice(0,2)
console.log('splice change in array so actual value of arr is :', arr)

const arr1 = [1,2,3,4,5]
// it will take slice(start, end) but end not included in return value
const cutSection = arr1.slice(1, 3);
console.log('portion or array', cutSection)

CodePudding user response:

You might've wanted to use slice to return everything upwards from index 15.

  • Related