-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransform-json.js
87 lines (75 loc) · 1.88 KB
/
transform-json.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*! transform-json v0.0.0 - MIT license */
'use strict';
var _ = require('lodash');
var transformJson = function (input, template) {
var output = _.cloneDeep(input);
var getPath = function (obj, path) {
if(!obj) {
return undefined;
}
else if(obj[path]) {
return obj[path];
}
else if(path.indexOf('.') > -1) {
var index = path.indexOf('.');
var key = path.substr(0,index);
var rest = path.substr(index+1);
return (getPath(obj[key], rest));
}
else {
return undefined;
}
};
var deleteFromPath = function (obj, path) {
if(obj[path]) {
delete obj[path];
}
else if(path.indexOf('.') > -1) {
var index = path.indexOf('.');
var key = path.substr(0,index);
var rest = path.substr(index+1);
deleteFromPath(obj[key], rest);
if(_.size(obj[key]) === 0) {
delete obj[key];
}
}
};
var setInPath = function (obj, path, insert) {
if(path.indexOf('.') > -1) {
var index = path.indexOf('.');
var key = path.substr(0,index);
var rest = path.substr(index+1);
if(!obj[key]) {
obj[key] = {};
}
setInPath(obj[key], rest, insert);
}
else {
obj[path] = insert;
}
};
var key;
for(key in template) {
var templateItem = template[key];
// get current value
var curValue = getPath(input, key);
if(!curValue) {
console.log('warning: path "' + key + '" not defined');
}
// delete from structure
deleteFromPath(output, key);
// fill new values
if(_.isArray(templateItem)) {
templateItem.forEach(function ( newKey ) {
setInPath(output, newKey, curValue);
});
}
else if (_.isString(templateItem)) {
setInPath(output, templateItem, curValue);
}
};
return output;
};
if ( typeof module !== "undefined" ) {
module.exports = transformJson;
}