简体   繁体   中英

How to get a value in an array that's in a list of arrays in javascript

To populate a HTML select field, I have this data:

let options = [
 {'label': '--Choose--', 'value':''},
 {'label': 'Linux', 'value':'linux'},
 {'label': 'OSX', 'value':'mac'},
 {'label': 'Windows 98', 'value':'win9x'},
 {'label': 'Windows XP', 'value':'winxp'}
]

Now with the value 'mac' I'd like to get the label 'OSX'.

Is it possible to get the label based on the value with this array in JSX in an elegant way?

eg 'mac' should give 'OSX'

I have ES6/ReactJS/Underscore/jQuery available.

Use filter to return a filtered array, grab the first element (which is an object), and then grab the value of label .

var label = options.filter(el => el.value === 'mac')[0].label;

DEMO

You can use Array.prototype.find() :

let option = options.find(el => el.value === 'mac');
let label = option ? option.label : undefined;

Thanks for the fast replies, I made it a bit more robust for my own usecase, where both 'mac' and options where unsure. Note the == instead of === because most of the time integers were compared to strings.

export function getLabelByValue(value, options) {
  if(value !== '' && value !== null && options.length > 0) {
      return options.filter(el => el.value == value)[0].label
  }
  return ''
}

let label = getLabelByValue('mac', options)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM