-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjectFlat-对象扁平化.js
More file actions
41 lines (36 loc) · 854 Bytes
/
Copy pathobjectFlat-对象扁平化.js
File metadata and controls
41 lines (36 loc) · 854 Bytes
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
function objectFlat(obj, result = {}) {
function isObject(target) {
return (target !== null && typeof target === 'object')
}
(function traverse(target, pkey = '') {
if (isObject(target)) Object.entries(target).forEach(([k, v]) => {
// 拼接key,数组的索引用 [] 替换 .
let ckey = pkey +
(Array.isArray(target) ? `[${k}]` : `${pkey && '.'}${k}`)
// 是对象就继续递归处理,不是对象则添加为result的属性
isObject(v) ? traverse(v, ckey) : (result[ckey] = v)
})
})(obj)
return result
}
// ==TEST==
let obj = {a: {b: {c: 1}}}
console.log(objectFlat(obj)) // { 'a.b.c': 1 }
obj = {
a: 1,
b: [1, 2, {c: true}],
c: {e: 2, f: 3},
g: null,
};
console.log(objectFlat(obj))
/*
{
a: 1,
'b[0]': 1,
'b[1]': 2,
'b[2].c': true,
'c.e': 2,
'c.f': 3,
g: null
}
*/