0

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

1 Answer 1

6

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 ''

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.