Home > front end >  How could I loop through an array and return the values ​dynamically?
How could I loop through an array and return the values ​dynamically?

Time:04-01

I have a problem, I have a function that returns values ​​from an array, but I wanted to return these values ​​dynamically.

const AvailableUserRoles = [
  {
    label: 'Administrator',
    value: 1
  },  
  {
    label: 'Count',
    value: 2
  },
  {
    label: 'Test',
    value: 5
  }
]

This is my function, which receives a parameter, which is a numeric value.

function getValue(item){
    if(item == AvailableUserRoles[0].value){
      return 'Administrator'

    }else if(item == AvailableUserRoles[1].value){
      return 'Count'

    }else if(item == AvailableUserRoles[3].value){
      return 'Test'

    }
  }      
}

I would like to do this check with dynamic values ​​as it would be easier to add new options later. No need to continue using AvailableUserRoles[].value

CodePudding user response:

Use Array.find to find the matching value dynamically.

const AvailableUserRoles = [
    {
        label: 'Administrator',
        value: 1
    },
    {
        label: 'Count',
        value: 2
    },
    {
        label: 'Test',
        value: 5
    }
]
function getValue(item) {
    const matchItem = AvailableUserRoles.find(node => node.value === item);
    return matchItem ? matchItem.label : "";
}
console.log(getValue(1)); // Returns 'Administrator'
console.log(getValue(2)); // Returns 'Count'
console.log(getValue(5)); // Returns 'Test'
console.log(getValue(6)); // Returns ''

CodePudding user response:

You could just do: return AvailableUserRoles[item - 1].label;. item is 1 more than the array's index and you can just return the corresponding label without having to check the value.

  • Related