get【获取对象属性值】🔥🔥🔥
描述
获取对象的属性的值,如果值为 undefined(即没找到),则返回默认值 v3.0.0-beta-1.0+
# 1.示例
import { get } from 'sf-utils2'
const info = {
id: 1,
name: '售后',
route: '',
parent_id: 0,
icon: '0',
type: 1,
list_order: 1,
is_show: true,
index: 1,
child: [
{
id: 777,
name: '用户代理结算',
route: '',
parent_id: 1,
icon: '0',
type: 1,
list_order: 15,
is_show: true,
index: '1-777',
child: [
{
id: 778,
name: '列表',
route: '/index/agency-settlement/list',
parent_id: 777,
icon: '0',
type: 1,
list_order: 1,
is_show: true,
index: '1-777-778'
},
{
id: 961,
name: '删除代理记录',
route: '',
parent_id: 777,
icon: '0',
type: 2,
list_order: 2,
is_show: false,
index: '1-777-961'
}
]
}
]
}
get(info, 'child[0].child[0].route') //输出 /index/agency-settlement/list
// 没有找到, 设置默认值
get(info, 'child[0].child[0].route.id.name', '这是默认值') // 输出 这是默认值
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
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
:::
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| obj | 原对象 | Object | 是 | |
| property | 属性名 | String | 是 | |
| defaultValue | 默认值 如果没有找到,设置默认值 | any | 否 | undefined |
# 3.源码
import _helperObjectFlatten from '@/_helper/_helperObjectFlatten'
/**
* 获取对象的属性的值,如果值为 undefined,则返回默认值
* @param {Object} obj
* @param {String} property
* @param {Any} defaultValue
* @returns {*}
*/
function get(obj, property, defaultValue) {
let result
_helperObjectFlatten(obj, (value, field) => {
if (field === property) {
result = value
return true
}
})
return result || defaultValue
}
export default get
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
上次更新: 2023/06/24, 19:35:48