-
Notifications
You must be signed in to change notification settings - Fork 3
/
flatten.js
55 lines (47 loc) · 1.18 KB
/
flatten.js
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
'use strict'
module.exports = flatten
function flatten(obj) {
var flattened = {}
var circlular = []
var circLoc = []
function _route(prefix, value) {
var i, len, type, keys, circularCheck, loc
if (value == null) {
if (prefix === "") {
return
}
flattened[prefix] = null
return
}
type = typeof value
if (typeof value == "object") {
circularCheck = circlular.indexOf(value)
if (circularCheck >= 0) {
loc = circLoc[circularCheck] || "this"
flattened[prefix] = "[Circular (" + loc + ")]"
return
}
circlular.push(value)
circLoc.push(prefix)
if (Array.isArray(value)) {
len = value.length
if (len == 0) _route(prefix + "[]", null)
for (i = 0; i < len; i++) {
_route(prefix + "[" + i + "]", value[i])
}
return
}
keys = Object.keys(value)
len = keys.length
if (prefix) prefix = prefix + "."
if (len == 0) _route(prefix, null)
for (i = 0; i < len; i++) {
_route(prefix + keys[i], value[keys[i]])
}
return
}
flattened[prefix] = value
}
_route("", obj)
return flattened
}