这个问题已经在这里有一个答案:
我想写一个JavaScript函数来显示多个下拉。正如你可以看到这一点。 State.data包含了整个API数据。这里this.state.data是对象的阵列。
我想作为排序依据的属性值返回累加器。值和标签是基本相同
getOptions(propertyName) {
return this.state.data.reduce((accum, elem, i) => {
const accumulator = [...accum];
if(!accumulator.some((e) => { return e.value === elem[propertyName]; })) {
if(elem[propertyName] !== '' && elem[propertyName] !== '-') {
accumulator.push({
id: i,
value: elem[propertyName],
label: elem[propertyName]
});
}
}
return accumulator;
}, []);
}
我只想使用纯JS来做。我可以使用lodash但我不能使用jQuery。我更感兴趣的是使用纯香草JS
如果你想用一个比较函数使用一个特定的属性进行比较:
data.sort(function (a,b) {
return a.propertyName > b.propertyName ? 1 : b.propertyName > a.propertyName ? -1 : 0;
})
而在一般情况如果要排序的字符串(不是对象)的按字母顺序排列只需拨打sort()
上的数据。呼叫reverse()
,如果你想在降序排列。