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
|
|
|
|
//
|
2015-12-16 05:21:13 -06:00
|
|
|
export default function flatten(target, opts): any {
|
2015-11-23 11:20:12 -06:00
|
|
|
opts = opts || {};
|
|
|
|
|
2017-12-20 05:33:33 -06:00
|
|
|
var delimiter = opts.delimiter || '.';
|
2015-11-23 11:20:12 -06:00
|
|
|
var maxDepth = opts.maxDepth || 3;
|
|
|
|
var currentDepth = 1;
|
|
|
|
var output = {};
|
|
|
|
|
|
|
|
function step(object, prev) {
|
|
|
|
Object.keys(object).forEach(function(key) {
|
|
|
|
var value = object[key];
|
|
|
|
var isarray = opts.safe && Array.isArray(value);
|
|
|
|
var type = Object.prototype.toString.call(value);
|
2017-12-20 05:33:33 -06:00
|
|
|
var isobject = type === '[object Object]';
|
2015-11-23 11:20:12 -06:00
|
|
|
|
|
|
|
var newKey = prev ? prev + delimiter + key : key;
|
|
|
|
|
|
|
|
if (!opts.maxDepth) {
|
|
|
|
maxDepth = currentDepth + 1;
|
|
|
|
}
|
|
|
|
|
2017-12-19 09:06:54 -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;
|
|
|
|
}
|