简体   繁体   English

如何在JavaScript中的数组列表中的数组中获取值

[英]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: 要填充HTML选择字段,我需要以下数据:

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'. 现在使用值“ mac”,我想获得标签“ OSX”。

Is it possible to get the label based on the value with this array in JSX in an elegant way? 是否可以使用JSX中的该数组基于该值获取标签?

eg 'mac' should give 'OSX' 例如,“ mac”应为“ OSX”

I have ES6/ReactJS/Underscore/jQuery available. 我有ES6 / ReactJS / Undercore / jQuery。

Use filter to return a filtered array, grab the first element (which is an object), and then grab the value of label . 使用filter返回过滤后的数组,获取第一个元素(这是一个对象),然后获取label的值。

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

DEMO 演示

You can use Array.prototype.find() : 您可以使用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. 感谢您的快速答复,对于我自己的用例(不确定'mac'和选项)的用例,我使其更加健壮。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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