0

Given I have these x3 checkbox input elements:

<input name="notifications.updatesCategoryNotifications.email_newsletter"" ... />
<input name="notifications.updatesCategoryNotifications.shopping" ... />
<input name="misc.updatesCategoryNotifications.profile" ... />

and wish to construct a data structure from its name attribute:

handleCheckboxChange(event) {
    const { target } = event;
    const type = target.name.split('.')[0]; // notifications
    const parent = target.name.split('.')[1]; // updatesCategoryNotifications
    const child = target.name.split('.')[2]; // email_newsletter

    // change-up the checked value in relevant object
    const activeArray = [...this.state[parent]];
    const activeArrayIdx = activeArray.map(item => item.name === child).indexOf(true);
    activeArray[activeArrayIdx].value = target.checked;

    // redo state and group things to send
    this.setState({
      dirtyData: {
        ...this.state.dirtyData,
        [type]: [
          activeArray[activeArrayIdx]
        ],
      },
    });
  }

Expected result: (this.state.dirtyData)

{
  "misc": [
    {
      "name": "profile",
    }
  ],
  "notifications": [
    {
      "name": "email_newsletter",
    },
    {
      "name": "shopping",
    }
  ]
}

Actual result: (this.state.dirtyData)

{
  "misc": [
    {
      "name": "profile",
    }
  ],
  "notifications": [
    {
      "name": "email_newsletter",
    },
  ]
}

Currently there is only ever one object being sent to the [type] property array again and again. I need it to add to it's own [type]. Think I'm just missing a trick with a spread operator?

Any help would be greatly appreciated!

Harry Lincoln
  • 614
  • 2
  • 9
  • 30

1 Answers1

0

Taking a guess here, since you are already modifying the values in activeArray you can just spread it:

// redo state and group things to send
this.setState({
  dirtyData: {
    ...this.state.dirtyData,
    [type]: [
      ...activeArray
    ],
  },
});

or just assign it, e.g [type]: activeArray,

thedude
  • 9,388
  • 1
  • 29
  • 30