Dan Knights
Dan Knights

Reputation: 8368

Pushing key value pairs to an object in Javascript

I have seven checkboxes, when one is checked or unchecked I want to push the currently checked boxes into the checkedCheckboxes object. When I console.log the key/value pairs inside the if statement I get the correct output, however, when I console.log() checkedCheckboxes after the updated values have been assigned I get this (the object at the bottom of the log):

console log

So I think there must something wrong with this line: checkedCheckboxes = {...key, ...colourCheckbox[key]};.

If anybody could tell me what, it would be a huge help.

Full code:

  // store checkbox values in an object;
  const colourCheckbox = {
    whiteBox: $('#white'),
    blueBox: $('#blue'),
    blackBox: $('#black'),
    redBox: $('#red'),
    greenBox: $('#green'),
    colourlessBox: $('#colourless'),
    multicolouredBox: $('#multicoloured')
  };

  // initialise object to store which checkboxes are checked
  let checkedCheckboxes = {};

  // store checked boxes in 'checkedBoxes'
  $('.colour-checkbox').change(() => {
    checkedCheckboxes.length = 0;
    for (const key in colourCheckbox) {
      if ($(colourCheckbox[key]).is(':checked')) {
        checkedCheckboxes = {...key, ...colourCheckbox[key]};
        console.log(key, colourCheckbox[key])
      }
    }
    console.log(checkedCheckboxes)
  });

Upvotes: 0

Views: 91

Answers (1)

Volodymyr Sitdikov
Volodymyr Sitdikov

Reputation: 424

You don't need to use spread operator if you doing it like this. Try to change your code to this

// store checkbox values in an object;
      const colourCheckbox = {
        whiteBox: $('#white'),
        blueBox: $('#blue'),
        blackBox: $('#black'),
        redBox: $('#red'),
        greenBox: $('#green'),
        colourlessBox: $('#colourless'),
        multicolouredBox: $('#multicoloured')
      };

      // initialise object to store which checkboxes are checked
      let checkedCheckboxes = {};

      // store checked boxes in 'checkedBoxes'
      $('.colour-checkbox').change(() => {
        checkedCheckboxes.length = 0;
        for (const key in colourCheckbox) {
          if ($(colourCheckbox[key]).is(':checked')) {
            checkedCheckboxes[key] = colourCheckbox[key];
            console.log(key, colourCheckbox[key])
          }
        }
        console.log(checkedCheckboxes)
      });

Upvotes: 1

Related Questions