![](/img/trans.png)
[英]How to get value from elements and use it inside of javascript options
[英]How to get the key value inside an array to use to populate dropdown options. Javascript
我有一个数组,我想加载OperatingSystem值作为下拉选项。
array = [
{count: "7", operatingSystem: "MacOS X"},
{count: "2", operatingSystem: "Windows 2012"},
{count: "2", operatingSystem: "FreeBSD / MacOS X"},
{count: "2", operatingSystem: "Linux 2.2-2.6"},
{count: "2"}];
这是我的工作方式:
renderFilterList(array) {
let array2=[];
array.map(function(obj, index) {
Object.keys(obj).forEach(function(val) {
array2.push({label: val.groupBy, key: index});
});
});
// the above does not work as I'm not getting the value of the key `operatingSystem` inside in the array loop. The value `operatingSystem` is dynamic and is subject to change depending on the data I get.
//following is a internal react component im using to get the values in the dropdown
<Dropdown
placeholder= "Select a value ..."
value={value}
listItems={array2}
key={key}
onSelect={this.onGroupValueSelect.bind()} />
</div>
}
在array2中,即时通讯试图获取此数据:
const array2 = [{label: "MacOS X", key:1},
{label: "Microsoft", key:2},
{label: "Linux", key:3},
{label: "Windows", key:4}];
如何获取键值,以便能够使用数组中的值填充下拉选项? 有任何想法吗?? 谢谢!!
我不知道您的Dropdown
组件的外观如何,但是鉴于该数组的值,我会这样做,
<select>
{ arr.map((item, index) => <option value={item.operatingSystem}>
{item.operatingSystem}</option>) }
</select>
工作小提琴https://jsfiddle.net/prakashk/69z2wepo/101360/#&togetherjs=Cyz8HtmxGq
请注意,如果需要,您可以先过滤没有operatingSystem
密钥的阵列。
如果您有动态键并且始终在第二个索引中,请执行以下`
<select>
{ arr.map((item, index) => {
const secondKey = Object.keys(item)[1];
return item[secondKey] && <option value={item[secondKey]}>
{item[secondKey]}</option> }) }
</select>
更新小提琴https://jsfiddle.net/prakashk/69z2wepo/101363/#&togetherjs=uBI1ey8mRs
对于您来说,您的数据似乎有问题:最后一项没有operatingSystem
密钥。 现在我们可以先进行filter
,然后进行map
,但这是次优的,因为它们在内部都遍历数据,因此导致两个循环
如果总是有可能没有operatingSystem
密钥的数据,那么我认为最好的选择是reduce
-它将循环减少到仅一次。
let array2 = array.reduce((result, value, index) => {
if (value.operatingSystem) {
result.push({label: value.operatingSystem, key: result.length + 1})
}
return result;
}, []);
我喜欢的是,您不必分别初始化array2 = []
然后push
它,而不是forEach
(或for
循环)。 相反,您将reduce
的结果直接分配给array2
。 请注意,我没有使用index
变量,但是您可以按如下所示编写result.push
行,如果这是您想要的,并且可能取决于您拥有的数据量和可能没有填充的operatingSystem
键,则可能会获得不同的键。 :
result.push({label: value.operatingSystem, key: index + 1})
如果您不小心包含了没有operatingSystem
密钥的条目,而它们实际上始终具有该密钥,则只需使用map
,而不是forEach
内部forEach
的方式:
let array2 = array.map((value, index) => {return {
label: value.operatingSystem,
key: index + 1
}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.