Ad

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?

e.g. 'mac' should give 'OSX'

I have ES6/ReactJS/Underscore/jQuery available.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad