2015-11-23 11:20:12 -06:00
|
|
|
// Copyright (c) 2014, Hugh Kennedy
|
|
|
|
// Based on code from https://github.com/hughsk/flat/blob/master/index.js
|
|
|
|
//
|
2019-08-12 09:11:06 -05:00
|
|
|
export default function flatten(target: object, opts?: { delimiter?: any; maxDepth?: any; safe?: any }): any {
|
2015-11-23 11:20:12 -06:00
|
|
|
opts = opts || {};
|
|
|
|
|
2018-08-26 14:52:57 -05:00
|
|
|
const delimiter = opts.delimiter || '.';
|
|
|
|
let maxDepth = opts.maxDepth || 3;
|
|
|
|
let currentDepth = 1;
|
2019-08-01 07:38:34 -05:00
|
|
|
const output: any = {};
|
2015-11-23 11:20:12 -06:00
|
|
|
|
2019-08-01 07:38:34 -05:00
|
|
|
function step(object: any, prev: string) {
|
2018-09-04 10:02:32 -05:00
|
|
|
Object.keys(object).forEach(key => {
|
2018-08-26 14:52:57 -05:00
|
|
|
const value = object[key];
|
|
|
|
const isarray = opts.safe && Array.isArray(value);
|
|
|
|
const type = Object.prototype.toString.call(value);
|
|
|
|
const isobject = type === '[object Object]';
|
2015-11-23 11:20:12 -06:00
|
|
|
|
2018-08-26 14:52:57 -05:00
|
|
|
const newKey = prev ? prev + delimiter + key : key;
|
2015-11-23 11:20:12 -06:00
|
|
|
|
|
|
|
if (!opts.maxDepth) {
|
|
|
|
maxDepth = currentDepth + 1;
|
|
|
|
}
|
|
|
|
|
2017-12-21 01:39:31 -06:00
|
|
|
if (!isarray && isobject && Object.keys(value).length && currentDepth < maxDepth) {
|
2015-11-23 11:20:12 -06:00
|
|
|
++currentDepth;
|
|
|
|
return step(value, newKey);
|
|
|
|
}
|
|
|
|
|
|
|
|
output[newKey] = value;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
step(target, null);
|
|
|
|
|
|
|
|
return output;
|
|
|
|
}
|