Search code examples
javascripthtmlarraysjavascript-objects

Javascript cannot map object with repetative values


I need to style specific elements by id using given object.

Keys and values in projectSkillsMap object corresponds to ids in html file. When user clicks on element with id listed in object keys function chooseProject() serves to style elements with ids listed in array of value corresponding to key.

Initial goal to remove class button_click from all of the buttons and add only to listed in the object.

const projectSkillsMap = {
  'project1': ['skill_2', 'skill4', 'skill5'],
  'project2': ['skill1', 'skill_2', 'skill4', 'skill5', 'skill6'],
  'project3': ['skill1', 'skill_2', 'skill3', 'skill4', 'skill5', 'skill6']
}

function chooseProject(key) {
  // adding accet to chosen group
  Object.keys(projectSkillsMap).map((i) => {
    if (i == key) {
      Object.entries(projectSkillsMap).map((il, value) => {
        if (il == i) {
          document.getElementById(value).classList.toggle('button_click')
        }
      })
    }
  })

  // removing accents from other groups
  Object.keys(projectSkillsMap).map((i) => {
    if (i !== key) {
      projectSkillsMap[`${i}`].map((el) => document.getElementById(`${el}`).classList.remove('button_click'))
    }
  })

  Object.values(projectSkillsMap).map((el) => {
    if (el !== key) {
      document.getElementById(el).classList.remove('button_click')
    }
  })
}

When user clicks on a button the chooseProject() function is triggered with one of the object keys. The problem is that document.getElementById(value).classList.toggle('button_click') does not work because of repetitive values among keys in my object.

I realized that when I changed my object and left only unique values for each key then the code work as expected.

Is there any way I can make it work?


Solution

  • Solution provided by Guy Incognito in comments. Look at the fiddle: jsfiddle.net/0k3zLjxb

    To sum up: initial goal was to remove the class from all the buttons and then add it to the ones in the object. There was no need to iterate over object keys or values via object methods, simple forEach() would do the trick.

    function chooseProject(key) {
    document.querySelectorAll(".skill_button").forEach(button => button.classList.remove('button_click'));
    projectSkillsMap[key].forEach(value => document.getElementById(value).classList.add('button_click'));
    
    }