繁体   English   中英

JS-获取相应的对象值

[英]JS - Get corresponding object value

在我的JavaScript中,我有一个对象:

var spirits = [
  { name: 'Bourbon (80 proof)', ethanol: 40, sugar: 0, acid: 0 },
  ...
  { name: 'Rum (100 proof)', ethanol: 50, sugar: 0, acid: 0 }
]

在我的html中,有一个<select> ,所有值都是带有饮料名称的字符串(即“波旁威士忌(80证明)”)。 我已经将此值存储在变量中。

我想log相应的乙醇百分比(40)。 这可能吗? 我考虑过翻遍对象并获取饮料名称的键,然后像spirits[key].ethanol一样记录spirits[key].ethanol

您必须 change事件处理程序绑定到您的输入。

另外,使用find方法以便在数组中搜索对象。 find方法接受提供的callback函数作为参数。

 var spirits = [ { name: 'Bourbon (80 proof)', ethanol: 40, sugar: 0, acid: 0 }, { name: 'Rum (100 proof)', ethanol: 50, sugar: 0, acid: 0 } ] spirits.forEach(function(item){ $('select').append('<option>'+item.name+'</option>'); }); $('select').change(function(){ var self=$(this); var obj=spirits.find(function(item){ return item.name==self.val(); }); console.log(obj.ethanol); }).trigger('change'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select></select> 

纯JavaScript版本。

 var spirits = [ { name: 'Bourbon (80 proof)', ethanol: 40, sugar: 0, acid: 0 }, { name: 'Rum (100 proof)', ethanol: 50, sugar: 0, acid: 0 } ] spirits.forEach(function(item){ var option=document.createElement('option'); option.text=item.name; document.getElementById('select').appendChild(option); }); document.getElementById('select').addEventListener('change',function(){ var value=this.value; var obj=spirits.find(function(item){ return item.name==value; }); console.log(obj.ethanol); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="select"> <option disabled selected>Select</option> </select> 

暂无
暂无

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

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