All files / arrayToObject arrayToObject.ts

100% Statements 8/8
100% Branches 1/1
100% Functions 2/2
100% Lines 7/7

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 35 36 37 38 39                                              1x             2x 2x 4x 4x 4x   2x    
/**
 * @description 数组转对象
 * @function arrayToObject
 * @param {array} [arr=[]] - 要转换的数组
 * @param {object} [fieldNames={key: 'value',value: 'label'}] - 转换结果对应数组中的key
 * @param {string} fieldNames.key - 要转换的数组的键名
 * @param {string} fieldNames.value - 要转换的数组的值名
 * @returns {object} 转换结果
 * @author liukun <919590347@qq.com>
 * @example
 * import { arrayToObject } from '@wont/utils'
 * arrayToObject([
 *  {
 *    value: 1,
 *    label: 'a',
 *  },
 *  {
 *    value: 2,
 *    label: 'b',
 *  },
 * ])  // return {a:1, b:2}
 */
 
export const arrayToObject = (
  arr: Record<string, string | number>[],
  fieldNames = {
    key: 'value',
    value: 'label',
  },
) => {
  const result = {}
  arr.forEach((item) => {
    const key = item[fieldNames.key]
    const value = item[fieldNames.value]
    result[key] = value
  })
  return result
}