forked from hughsk/flat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (57 loc) · 1.96 KB
/
index.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var flat = module.exports = {}
var flatten = flat.flatten = function (target, opts) {
var output = {}
, opts = opts || {}
, delimiter = opts.delimiter || '.'
function getkey(key, prev) {
return prev ? prev + delimiter + key : key
};
function step(object, prev) {
Object.keys(object).forEach(function(key) {
var isarray = opts.safe && Array.isArray(object[key])
, type = Object.prototype.toString.call(object[key])
, isobject = (type === "[object Object]" || type === "[object Array]")
if (!isarray && isobject) {
return step(object[key]
, getkey(key, prev)
)
}
output[getkey(key, prev)] = object[key]
});
};
step(target)
return output
};
var unflatten = flat.unflatten = function (target, opts) {
var opts = opts || {}
, delimiter = opts.delimiter || '.'
, result = {}
if (Object.prototype.toString.call(target) !== '[object Object]') {
return target
}
function getkey(key) {
var parsedKey = parseInt(key)
return (isNaN(parsedKey) ? key : parsedKey)
};
Object.keys(target).forEach(function(key) {
var split = key.split(delimiter)
, firstNibble
, secondNibble
, recipient = result
firstNibble = getkey(split.shift())
secondNibble = getkey(split[0])
while (secondNibble !== undefined) {
if (recipient[firstNibble] === undefined) {
recipient[firstNibble] = ((typeof secondNibble === 'number') ? [] : {})
}
recipient = recipient[firstNibble]
if (split.length > 0) {
firstNibble = getkey(split.shift())
secondNibble = getkey(split[0])
}
}
// unflatten again for 'messy objects'
recipient[firstNibble] = unflatten(target[key])
});
return result
};