-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (54 loc) · 1.57 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
var _ = require('lodash');
module.exports = function(results, objects, strict) {
strict = !!strict;
if (!results)
return (strict) ? undefined : {};
if (!objects)
return results;
if (!_.isArray(objects))
if (_.isString(objects))
objects = [objects];
else
return results;
var predicate = function(value, index, array) {
return _.isEmpty(value) && _.isPlainObject(value);
};
if (_.isArray(results)) {
var res = [];
for (var i = 0; i < results.length; i++) {
res.push(__buildObj(results[i],objects));
}
return res;
} else if (_.isObject(results)) {
return __buildObj(results, objects);
} else {
return (strict) ? undefined : {};
}
function __buildObj(results, objects) {
var obj = {};
objects.forEach(function(group) {
obj[group] = {};
});
// Iterate over object properties
var r = new RegExp('__(.+?)__(.+)');
_.forOwn(results, function(value, key) {
var matches = r.exec(key);
if (matches !== null && _.has(obj, matches[1]) && matches.length == 3 && matches[1].length > 0 && matches[2].length > 0) {
if (!strict) {
obj[matches[1]][matches[2]] = value;
} else if (typeof value !== "undefined" && value != null) {
obj[matches[1]][matches[2]] = value;
}
} else {
obj[key] = value;
}
});
if (strict) {
_.forOwn(obj, function(value, key) {
if (!value && _.includes(objects, key))
delete obj[key];
});
}
return (strict) ? _(obj).omitBy(predicate).value() : obj;
}
};