Last active
June 10, 2020 10:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, []); | |
}; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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" | |
} | |
} | |
] | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Testing
flatten()
function:https://www.yourjs.com/console/?gist=77c370d62724935f2473c9b70fbe2ecc&file=~example.js&skipIntro=1