sf-utils2 sf-utils2
版本v3.3.3-beta1
首页
  • 01.快速开始 🔥
  • 02.基础-Base
  • 03.对象-Object
  • 04.数组-Array
  • 05.方法-Function
  • 06.字符串-String
  • 07.数学-Math
  • 08.dom
  • 09.拓展
  • webpack5.x教程学习 (opens new window)
  • 例子
  • 教程 🔥
  • 例子配置
企业级后台模版 (opens new window)
版本v3.3.3-beta1
首页
  • 01.快速开始 🔥
  • 02.基础-Base
  • 03.对象-Object
  • 04.数组-Array
  • 05.方法-Function
  • 06.字符串-String
  • 07.数学-Math
  • 08.dom
  • 09.拓展
  • webpack5.x教程学习 (opens new window)
  • 例子
  • 教程 🔥
  • 例子配置
企业级后台模版 (opens new window)
  • 快速开始

  • 基础-Base

  • 对象-Object

  • 数组-Array✨✨✨

    • 序言 👏
    • uniq 【数组去重】
    • arrayToMap 【数组转成Map】
      • 1.示例
      • 2.入参说明
        • options 对象
      • 3.源码
    • arrayToObj 【数组转成obj】
    • chunk 【数组切割】
    • compact 【去除数组中无效值】
    • remove 【数组中移除一个元素】
    • shuffle 【数组随机打乱】
    • groupBy 【分组】
    • compactIsNoNullable 【去除数组中null/undefined/NaN】
    • arrayDiff【比较数组差异】🔥🔥
    • differenceBy【获取新增数组】🔥
    • intersection 【数组交集】
    • matchSubListGroup
    • listToTree【列表转树形】🔥🔥🔥
    • treeToList【树型转列表】🔥🔥🔥
    • eachTree【遍历树形结构】🔥🔥🔥
    • filterTree【过滤树形结构】🔥🔥🔥
    • childNodesInList【列表中获取某个下所有后代节点】🔥
    • parentNodesInTree【tree中获取所有祖先节点】 🔥
    • formatStrategyIdsInTree【树形数据中只选中父节点】 🔥
    • range 【序号列表生成函数】
  • 方法-Function

  • 字符串-String

  • 数学-Math

  • 文件-Buffer

  • 节点-dom

  • 拓展

  • nodejs

目录

arrayToMap 【数组转成Map】

描述

数组转成 Map v3.0.9+

# 1.示例

import { arrayToMap } from 'sf-utils2'

const list = [
 { empId: 1, empName: '蔡徐坤'},
 { empId: 2, empName: '小明'},
 { empId: 3, empName: '小红'},
]

// 根据属性名转化
arrayToMap(list, 'empId')
// 输出
[[Entries]]
  0: {1 => Object}
  1: {2 => Object}
  2: {3 => Object}
size: 3


// 不传属性名
const list = [1, 2, 3, '4']
arrayToMap(list)
// 输出
[[Entries]]
  0: {1 => 1}
  1: {2 => 2}
  2: {3 => 3}
  3: {3 => '4'}
size: 4


// 返回属性值为数组
arrayToMap(list, 'empId', {valueType: 'array'})
// 输出
[[Entries]]
  0: {1 => [{empId: 1, empName: '蔡徐坤'}]}
  1: {2 => [{empId: 2, empName: '小明'}]}
  2: {3 => [{empId: 3, empName: '小红'}]}
size: 3


// 通过function,函数自定义
arrayToMap(list, (map, item, index) => {
    map.set(item.empId, item)
})

// 输出
[[Entries]]
  0: {1 => [{empId: 1, empName: '蔡徐坤'}]}
  1: {2 => [{empId: 2, empName: '小明'}]}
  2: {3 => [{empId: 3, empName: '小红'}]}
size: 3


// 多个属性名
const list = [
  { empId: 1, empName: '蔡徐坤' },
  { empId: 2, empName: '小明' },
  { empId: 3, empName: '蔡徐坤' },
]
console.log(arrayToMap(list, ['empId', 'empName']))
// =>
// [
//  ['1|蔡徐坤', {empId: 1, empName: '蔡徐坤'}],
//  ['2|小明', {empId: 2, empName: '小明'}],
//  ['3|蔡徐坤', {empId: 3, empName: '蔡徐坤'}]
// ]

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

# 2.入参说明

参数 说明 类型 是否必填
array 原数组 Array --------
property 属性名或回调函数 Array、Function、string[] --------
options 配置参数详情见下 👇 Object --------

# options 对象

参数 说明 类型 是否必填 默认值
valueType 每一项返回值类型是对象还是数组,前提建立当设置 proerty 是字符串有值时 object\|array 否 object
retainKeyWithNull 是否保留未定义的属性值 boolean v3.1.4+ 否 false

# 3.源码

源码,点开查看 👈
import isArray from '@/base/isArray'
import isFunction from '@/base/isFunction'
import isString from "@/base/isString";
import isNullable from "@/base/isNullable";

/**
 * 根据数组 从对象中获取属性,并且以|进行分割
 * @param {object} object
 * @param {string|string[]} properties
 * @returns {*}
 */
export const getPropValue = (object, properties) => {
  if (isString(properties)) return object?.[properties]
  return properties.map(prop => object?.[prop]).filter(Boolean).join(`|`)
}

/**
 * 将数组转成Map类型
 * @param {Object[]} array 数组
 * @param {string|Function|string[]} [property] 主键
 * @param {{valueType?: 'object' | 'array', retainKeyWithNull?: boolean}} [options] 是否保留未定义的属性值
 * @return {Map<any, any>|{}|*}
 * @example
 *
 * const list = [
 *  {empId: 1, empName: '蔡徐坤'},
 *  {empId: 2, empName: '小明'}
 * ]
 * arrayToMap(list, 'empId')
 * =>
   [[Entries]]
    0: {1 => Object}
    1: {2 => Object}
   size:2
 *
 * const list = [
 *  1, 2, 3, '4'
 * ]
 * arrayToMap(list)
   =>
   [[Entries]]
   0: {1 => 1}
   1: {2 => 2}
   2: {3 => 3}
   3: {'4' => '4'}
   size:4
 *
 */
function arrayToMap(array = [], property, options = { valueType: 'object', retainKeyWithNull: false }) {
  if (isArray(array)) {
    // 如果property是Function
    if (isFunction(property)) {
      const map = new Map()
      array.forEach((v, vi) => property(map, v, vi))
      return map
    }
    const valueType = String(options?.valueType).toLowerCase() || 'object'
    // 非Function,且property存在
    if (property) {
      return array.reduce((pre, cur) => {
        let value = getPropValue(cur, property)
        if (options.retainKeyWithNull && isNullable(value))  value = 'undefined'
        if (value) {
          if (valueType === 'array') {
            if (!isArray(pre.get(value))) pre.set(value, [])
            pre.get(value).push(cur)
          } else {
            pre.set(value, cur)
          }
        }
        return pre
      }, new Map())
    }
    // property不存在时
    return array.reduce((pre, cur) => {
      if (options.retainKeyWithNull && isNullable(value)) cur = 'undefined'
      if (cur) {
        if (valueType === 'array') {
          if (!isArray(pre.get(cur))) pre.set(cur, [])
          pre.get(cur).push(cur)
        } else {
          pre.set(cur, cur)
        }
      }
      return pre
    }, new Map())
  }
  return new Map()
}
export default arrayToMap

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
上次更新: 2024/01/16, 00:14:12
uniq 【数组去重】
arrayToObj 【数组转成obj】

← uniq 【数组去重】 arrayToObj 【数组转成obj】→

Theme by Vdoing | Copyright © 2022-2025 bianpengfei
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×