@coderich/util 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.js +30 -1
package/package.json
CHANGED
package/src/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
const FS = require('fs');
|
|
2
2
|
const Path = require('path');
|
|
3
3
|
const ChildProcess = require('child_process');
|
|
4
|
-
const { set, isEqual } = require('lodash');
|
|
4
|
+
const { get, set, isEqual } = require('lodash');
|
|
5
5
|
const { ObjectId } = require('bson');
|
|
6
6
|
|
|
7
|
+
exports.get = get;
|
|
7
8
|
exports.set = set;
|
|
8
9
|
exports.isEqual = isEqual;
|
|
9
10
|
exports.ObjectId = ObjectId;
|
|
@@ -75,8 +76,36 @@ exports.flatten = (mixed, options = {}) => {
|
|
|
75
76
|
exports.unflatten = (data, options = {}) => {
|
|
76
77
|
const typeFn = options.safe ? exports.isPlainObject : exports.isPlainObjectOrArray;
|
|
77
78
|
|
|
79
|
+
const compactArrays = (prev, key, value) => {
|
|
80
|
+
const parts = key.split('.');
|
|
81
|
+
const last = parts.at(-1);
|
|
82
|
+
|
|
83
|
+
if (/^\d+$/.test(last)) {
|
|
84
|
+
// This is a numeric segment — treat parent as a dense array
|
|
85
|
+
const parentPath = parts.slice(0, -1).join('.');
|
|
86
|
+
|
|
87
|
+
// Get existing parent, or create it as an array
|
|
88
|
+
let parent = parentPath ? exports.get(prev, parentPath) : prev;
|
|
89
|
+
if (!Array.isArray(parent)) {
|
|
90
|
+
parent = [];
|
|
91
|
+
if (parentPath) {
|
|
92
|
+
exports.set(prev, parentPath, parent);
|
|
93
|
+
} else {
|
|
94
|
+
// Top-level array
|
|
95
|
+
return [value]; // shortcut if root is just an array
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
parent.push(value);
|
|
100
|
+
return prev;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return exports.set(prev, key, value);
|
|
104
|
+
};
|
|
105
|
+
|
|
78
106
|
return exports.map(data, (el) => {
|
|
79
107
|
return typeFn(data) ? Object.entries(exports.flatten(el, options)).reduce((prev, [key, value]) => {
|
|
108
|
+
if (options.compactArrays) return compactArrays(prev, key, value);
|
|
80
109
|
return exports.set(prev, key, value);
|
|
81
110
|
}, {}) : el;
|
|
82
111
|
});
|