Files
grafana/packages/grafana-ui/src/components/Select/utils.ts
kay delaney 56db402d0f Chore: Upgrade typescript to 4.1 (#29493)
* Chore: Upgrade typescript to 4.1
2020-12-03 15:05:59 +00:00

46 lines
1.2 KiB
TypeScript

import { SelectableValue } from '@grafana/data';
import { SelectableOptGroup } from './types';
/**
* Normalize the value format to SelectableValue[] | []. Only used for single select
*/
export const cleanValue = (
value: any,
options: Array<SelectableValue | SelectableOptGroup | SelectableOptGroup[]>
): SelectableValue[] | [] => {
if (Array.isArray(value)) {
return value.filter(Boolean);
}
if (typeof value === 'object' && value !== null) {
return [value];
}
if (typeof value === 'string' || typeof value === 'number') {
const selectedValue = findSelectedValue(value, options);
if (selectedValue) {
return [selectedValue];
}
}
return [];
};
/**
* Find the label for a string|number value inside array of options or optgroups
*/
export const findSelectedValue = (
value: string | number,
options: Array<SelectableValue | SelectableOptGroup | SelectableOptGroup[]>
): SelectableValue | null => {
for (const option of options) {
if ('options' in option) {
let found = findSelectedValue(value, option.options);
if (found) {
return found;
}
} else if ('value' in option && option.value === value) {
return option;
}
}
return null;
};