All files / formatOptions formatOptions.ts

100% Statements 4/4
100% Branches 1/1
100% Functions 2/2
100% Lines 2/2

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                                              1x           4x        
/**
 * @description 格式化数组对象为value、label形式,方便ui组件下拉
 * @function formatOptions
 * @param {array} arr - 要格式化的数组
 * @param {object} [fieldNames={value: 'key',label: 'value'}] - 转换结果对应数组中的key
 * @param {string} fieldNames.key - 要转换的数组的键名
 * @param {string} fieldNames.value - 要转换的数组的值名
 * @returns {array} 转换结果
 * @author liukun <919590347@qq.com>
 * @example
 * import { formatOptions } from '@wont/utils'
 * formatOptions([
 *  {
 *    key: 'a',
 *    value: 1,
 *  },
 *  {
 *    key: 'b',
 *    value: 2,
 *  },
 * ])  // return [{value: 'a', label: 1}, {value: 'b', label: 2}]
 */
 
export const formatOptions = (
  arr: Record<string, string | number>[],
  fieldNames = {
    value: 'key',
    label: 'value',
  },
) => arr.map((item) => ({
  value: item[fieldNames.value],
  label: item[fieldNames.label],
}))