-
Notifications
You must be signed in to change notification settings - Fork 0
/
deepToFlatObject.js
31 lines (25 loc) · 1.06 KB
/
deepToFlatObject.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
const isEmpty = require('lodash/isEmpty');
const isPrimitive = require('./helpers/isPrimitive');
const hasPrototype = require('./helpers/hasPrototype');
function deepToFlatObject(originalObj, options = {}) {
const preservePrototypes = options.preservePrototypes ?? true;
const pathPrefix = options.pathPrefix ?? '';
const fullPathObj = {};
function depthFirstObjTraversal(obj, path = '') {
if (!isEmpty(obj)) {
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object' && !isEmpty(obj[key]) && !(preservePrototypes && hasPrototype(obj[key])) && !(obj[key] instanceof Date)) {
const deepPath = path ? `${path}.${key}` : key;
depthFirstObjTraversal(obj[key], deepPath);
} else if (isPrimitive(obj[key])
|| obj[key] instanceof Date
|| (preservePrototypes && hasPrototype(obj[key]))) {
fullPathObj[path ? `${path}.${key}` : key] = obj[key];
}
});
}
}
depthFirstObjTraversal(originalObj, pathPrefix);
return fullPathObj;
}
module.exports = deepToFlatObject;