[英]Extract a value property from either an array OR object using Javascript
I have some options in a dropdown box on my website which are then sent via webhook for me to extract details from. 我在网站的下拉框中有一些选项,然后通过webhook发送给我,以从中提取详细信息。 I am trying to extract the value from the ageId object. 我正在尝试从ageId对象中提取值 。
But depending on the dropdown item selected, it is either placed into an array or an object with some other details added. 但是根据所选的下拉项,它可以放置在数组中,也可以是添加了其他一些详细信息的对象。
When the Adult option is chosen, ageId is: [ { i: 0, value: '25', label: 'Adult' } ]
选择“ 成人”选项后,ageId为: [ { i: 0, value: '25', label: 'Adult' } ]
'25 [ { i: 0, value: '25', label: 'Adult' } ]
When the Senior option is chosen, ageId is: { '1': { i: 1, value: '65', label: 'Senior' } }
选择“ 高级”选项时,ageId为: { '1': { i: 1, value: '65', label: 'Senior' } }
'65 { '1': { i: 1, value: '65', label: 'Senior' } }
Before I added more dropdown options, the following worked to extract the required property of 25 在添加更多下拉选项之前,以下工作提取了25的必需属性
const ageMinimum = event.ageId[0].value[Object.keys(event.ageId[0].value)[0]].value;
How can I extract the value (eg.25 or 65) property every time regardless of the dropdown selected and the subsequent changing syntax? 我如何每次选择提取下拉列表和随后更改语法时都提取值 (例如25或65)属性?
You could try: 您可以尝试:
var adult = [ { i: 0, value: '25', label: 'Adult' } ];
var senior = { '1': { i: 1, value: '65', label: 'Senior' } };
var tmp = senior; // Or adult
var ageMinimum = (Array.isArray(tmp) ? tmp[0] : tmp[Object.keys(tmp)[0]]).value; // Edited to work with flexible first object property names
console.log(ageMinimum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.