json-order
Version:
Control the order of properties in JSON via a lookup object - including nested properties.
46 lines (45 loc) • 1.59 kB
JavaScript
;
/* eslint-disable @typescript-eslint/ban-types */
Object.defineProperty(exports, "__esModule", { value: true });
var traverseObject = function (obj, map, parentKey, separator) {
var childKeys = Object.keys(obj);
if (childKeys.length === 0) {
return;
}
// Ignore storing keys for arrays
if (!Array.isArray(obj)) {
map["" + parentKey] = childKeys;
}
childKeys.forEach(function (childKey) {
var value = obj[childKey];
if (typeof value === 'object') {
traverseObject(value, map, "" + parentKey + separator + childKey, separator);
}
});
};
/**
* Parse a JSON string and generate a map
*
* @param jsonString a json string
* @param prefix a non-empty `string` that controls what the key prefix value is in the generated map. Defaults to `$`.
* @param separator a non-empty `string` that controls what the key separator is in the generated map. Defaults to `~`.
* @returns an object containing the parsed `object: T` and the `map: PropertyMap`
*/
var parse = function (jsonString, prefix, separator) {
if (prefix === void 0) { prefix = '$'; }
if (separator === void 0) { separator = '~'; }
if (prefix.length < 1) {
throw new Error('Prefix should not be an empty string.');
}
if (separator.length < 1) {
throw new Error('Separator should not be an empty string.');
}
var obj = JSON.parse(jsonString);
var map = {};
traverseObject(obj, map, prefix, separator);
return {
object: obj,
map: map,
};
};
exports.default = parse;