Skip to content

Instantly share code, notes, and snippets.

@westc
Last active June 10, 2020 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/77c370d62724935f2473c9b70fbe2ecc to your computer and use it in GitHub Desktop.
Save westc/77c370d62724935f2473c9b70fbe2ecc to your computer and use it in GitHub Desktop.
Assuming that the value passed to flattenKeys() is not recursive, this function will recursively flatten all of the underlying keys for objects and arrays.
var flattenKeys;
(function() {
function recurseFlat(value, path) {
var iterType = Array.isArray(value)
? 'A'
: (value && 'object' === typeof value);
if (iterType) {
var keys = iterType === 'A'
? value.map(function(v,i){return i})
: Object.keys(value);
return keys.reduce(function(returnValue, key) {
var innerValue = value[key];
var newPath = path.concat([encodeKey(key)]);
if (innerValue && 'object' === typeof innerValue) {
returnValue = Object.assign(returnValue, recurseFlat(innerValue, newPath));
}
else {
returnValue[newPath.join('.')] = innerValue;
}
return returnValue;
}, {});
}
return value;
}
function encodeKey(key) {
return (key + "").replace(/[\\\.]/g, '\\$&');
}
flattenKeys = function(value) {
return recurseFlat(value, []);
};
})();
// HIDE \\
console.load('local://flattenKeys.js');
//\\
flattenKeys({
name: {
first: "John",
last: "Jacob"
},
age: 56,
gender: "Male",
relatives: [
{
name: {
first: "Tina",
last: "Jacobs"
}
},
{
name: {
first: "Sarah",
last: "Connor"
}
}
]
});
@westc
Copy link
Author

westc commented Jun 10, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment