forked from watson/flatten-obj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (40 loc) · 1.2 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
'use strict'
var isObj = require('isobj')
module.exports = function (options) {
options = options || {}
var blacklist = options.blacklist || []
var separator = options.separator == null ? '.' : options.separator
var onlyLeaves = options.onlyLeaves && true
if (options.brackets == null) {
var brackets = ['', '']
} else {
var brackets = options.brackets == true ? ['[', ']'] : options.brackets.split('')
if (options.separator == null) {
separator = '';
}
}
return flatten
function flatten (obj) {
var result = {}
iterator(obj, '', result)
return result
}
function iterator (obj, prefix, flattened) {
var keys = Object.keys(obj)
for (var n = 0; n < keys.length; n++) {
var key = keys[n]
var keyWrapped = '[' + key + ']'
var val = obj[keys[n]]
if (isObj(val) && !isBlacklisted(val)) {
iterator(val, prefix + (prefix ? keyWrapped : key) + separator, flattened)
continue
}
onlyLeaves ? flattened[keyWrapped] = val : flattened[prefix + keyWrapped] = val
}
}
function isBlacklisted (obj) {
for (var i = 0; i < blacklist.length; i++) {
if (obj instanceof blacklist[i]) return true
}
}
}