Skip to content

Commit f2f9f09

Browse files
author
Sebastian Roming
committed
finalized the [...].json() method
1 parent 55fd19e commit f2f9f09

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

index.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
22
/* eslint-disable array-callback-return, guard-for-in */
33

4+
const _ = require('lodash.get');
5+
46
const getDeepKeys = obj => {
57
let keys = [];
68
for (const key in obj) {
@@ -17,7 +19,7 @@ const getDeepKeys = obj => {
1719
return keys;
1820
};
1921

20-
module.exports = (obj1, obj2) => {
22+
const jsonMultilevelDelta = (obj1, obj2) => {
2123
const objects = [getDeepKeys(obj1), getDeepKeys(obj2)];
2224
const deltaKeys = [];
2325

@@ -31,3 +33,31 @@ module.exports = (obj1, obj2) => {
3133

3234
return deltaKeys;
3335
};
36+
37+
const stringToObj = (path, value, obj) => {
38+
const parts = path.split('.');
39+
const last = parts.pop();
40+
let part = null;
41+
42+
while (parts.length) {
43+
part = parts.shift();
44+
if (typeof obj[part] !== 'object') {
45+
obj[part] = {};
46+
}
47+
obj = obj[part];
48+
}
49+
obj[last] = value;
50+
};
51+
52+
module.exports = (obj1, obj2) => jsonMultilevelDelta(obj1, obj2);
53+
module.exports.json = (obj1, obj2) => {
54+
const keys = jsonMultilevelDelta(obj1, obj2);
55+
56+
const jsonObj = {};
57+
keys.forEach(key => {
58+
const value = (typeof _(obj1, key) === 'undefined') ? _(obj2, key) : _(obj1, key);
59+
stringToObj(key, value, jsonObj);
60+
});
61+
62+
return jsonObj;
63+
};

0 commit comments

Comments
 (0)