Created
June 1, 2019 23:15
-
-
Save Jarvie8176/bbc1715220768f80e389c47c3b2a1a68 to your computer and use it in GitHub Desktop.
denormalize nested json to key value pairs
This file contains hidden or 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
import _ = require("lodash"); | |
test("foo", () => { | |
const input = { | |
a: { c: { d: 1, e: 2 } }, | |
f: { g: 3 } | |
}; | |
console.log(parserRunner(input)); | |
}); | |
function parserRunner(input: any) { | |
const result = <any>[]; | |
parser(input, [], result); | |
let parsed = _.chain(result) | |
.filter(i => !_.isUndefined(i[1])) | |
.sortBy(i => i[0]) | |
.value(); | |
let keys = _.map(parsed, item => item[0]); | |
let vals = _.map(parsed, item => item[1]); | |
return _.zipObject(keys, vals); | |
} | |
function parser(input: {}, paths: string[], results: any[]) { | |
if (typeof input !== "object") return input; | |
_.each(input, (val, key) => { | |
let clonedPaths = _.clone(paths); | |
clonedPaths.push(key); | |
let currVal = parser(val, clonedPaths, results); | |
results.push([clonedPaths.join("."), currVal]); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment