-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapKeys.js
More file actions
49 lines (43 loc) · 1.26 KB
/
mapKeys.js
File metadata and controls
49 lines (43 loc) · 1.26 KB
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
function mapKey (object, oldKey, newKey) {
const oldKeyFragments = oldKey.split('.')
const value = oldKeyFragments.reduce(
(subObject, subKey, index) => {
if (subObject && subObject.hasOwnProperty(subKey)) {
const tempValue = subObject[subKey]
if (index === oldKeyFragments.length - 1) delete subObject[subKey]
return tempValue
}
else {
return undefined
}
},
object
)
if (typeof value === 'undefined') return
const fragments = newKey.split('.')
fragments
.reduce(
(subObject, subKey, index) => {
if (typeof subObject[subKey] === 'undefined') subObject[subKey] = {}
if (index === fragments.length - 1) subObject[subKey] = value
return subObject[subKey]
},
object
)
}
module.exports = (options) => {
const {in: object} = options
const objectClone = Object.assign({}, object) // Clone object
let {mappings} = options
if (!Array.isArray(mappings)) mappings = [mappings]
mappings.forEach(map => {
const {to: newKey} = map
let {from: oldKeys} = map
if (!Array.isArray(oldKeys)) oldKeys = [oldKeys]
oldKeys.forEach(oldKey => {
mapKey(objectClone, oldKey, newKey)
delete objectClone[oldKey]
})
})
return objectClone
}