UNPKG

ts-prime

Version:

A utility library for JavaScript and Typescript.

71 lines (70 loc) 2.63 kB
"use strict"; // stackoverflow.com/questions/44134212/best-way-to-flatten-js-object-keys-and-values-to-a-single-depth-array var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); function flattenObject(obj, options) { var defaultOptions = __assign({ separator: '.' }, (options || {})); function flt(obj, prefix, result) { if (prefix === void 0) { prefix = ''; } if (result === void 0) { result = null; } result = result || {}; // Preserve empty objects and arrays, they are lost otherwise if (prefix && typeof obj === 'object' && obj !== null && Object.keys(obj).length === 0) { result[prefix] = Array.isArray(obj) ? [] : {}; return result; } prefix = prefix ? prefix + ("" + defaultOptions.separator) : ''; for (var i in obj) { if (Object.prototype.hasOwnProperty.call(obj, i)) { if (typeof obj[i] === 'object' && obj[i] !== null) { // Recursion on deeper objects flt(obj[i], prefix + i, result); } else { result[prefix + i] = obj[i]; } } } return result; } return flt(obj); } exports.flattenObject = flattenObject; function unFlattenObject(obj) { var result = {}; var _loop_1 = function (i) { if (Object.prototype.hasOwnProperty.call(obj, i)) { var keys_1 = i.match(/^\.+[^.]*|[^.]*\.+$|(?:\.{2,}|[^.])+(?:\.+$)?/g); // Just a complicated regex to only match a single dot in the middle of the string if (keys_1 == null) return { value: result }; keys_1.reduce(function (r, e, j) { return (r[e] || (r[e] = isNaN(Number(keys_1[j + 1])) ? keys_1.length - 1 === j ? obj[i] : {} : [])); }, result); } }; for (var i in obj) { var state_1 = _loop_1(i); if (typeof state_1 === "object") return state_1.value; } return result; } exports.unFlattenObject = unFlattenObject;