Skip to content
Advertisement

How can I change the value of an item in an array based on multiple conditions?

I am trying to change the value of an item in array, based on matching other items in the array. The array might contain details of the section (non-unique), a unique ID, and a value I wish to change (in this case a ‘selected’ flag). The goal is to be able to have multiple items which can have their selected flag. Within any single section, only one item could be ‘selected’ but multiple sections could have an individual item ‘selected’. Conceptually, I think this could be thought of in the same way as having multiple groups of radio buttons.

The ultimate aim is to be able to use state to remember the selections made in a component that is created using props. I’m keen to understand not simply copy. I’ll get my head around state mutations next, but better to solve this problem first.

So, take an array like:

    menuItems: [
    {
      section: 'National',
      id: 'First item',
      selected: false
    },
    {
      section: 'National',
      id: 'Second item',
      selected: false
    },
    {
      section: 'National',
      id: 'Third item',
      selected: true
    },
    {
      section: 'Local',
      id: 'Fourth item',
      selected: false
    },
    {
      section: 'Local',
      id: 'Fifth item',
      selected: false
    },
    {
      section: 'Local',
      id: 'Sixth item',
      selected: true
    }
  ]

And some search strings like:

      searchSection: 'National',
      searchId: 'First item'

How would I create a function that could change the selected flag of the item with id: First item to true, the others (second, third item) to false, and don’t change anything in the ‘Local’ section?

I have tried to get my head around using forEach loops to no avail, even though this feels the right approach. Using findIndex for the section seems destined to fail as there are multiple items to be found.

First SO question – so pre-emptive apologies if problems with the way I have asked. I’m using Vue3. All advice appreciated.

Advertisement

Answer

Loop through the items testing for the proper section. With the section, if there is an id match, set selected to true, otherwise set selected to false:

methods: {
  flag(searchSection, searchId) {
    this.menuItems.forEach(item => {
       if (item.section === searchSection) {
          item.selected = item.id === searchId;
       }
    });
  }
}

Call the function:

this.flag('National', 'First item');
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement