Created
April 19, 2020 08:46
-
-
Save frandi/c0a40d52cd219f0635054c79d989828c to your computer and use it in GitHub Desktop.
Sample of functions in converting nested objects into flatten object array
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
interface NestedKeyValuePair { | |
key: string, | |
value: string, | |
next: NestedKeyValuePair | |
} | |
interface KeyValuePair { | |
key: string, | |
value: string | |
} | |
function flatten(input: NestedKeyValuePair) : KeyValuePair[] { | |
// clone the input | |
const original = {...input} | |
let output = [] | |
var current = original | |
while (current != undefined) { | |
output.push({ key: current.key, value: current.value }) | |
current = current.next | |
} | |
return output | |
} | |
function toNestedKeyValuePair(input: KeyValuePair[]) : NestedKeyValuePair { | |
// clone the input | |
const original = input.map(obj => obj) | |
let inputLength = original.length | |
var parent = {} as NestedKeyValuePair | |
original.reverse().forEach((obj, index) => { | |
let current = parent | |
current.key = obj.key | |
current.value = obj.value | |
let hasParent = inputLength > index + 1 | |
if (hasParent) { | |
parent = { next: current } as NestedKeyValuePair | |
} | |
}) | |
return parent | |
} | |
// the testing object | |
const tests = { | |
key: 'a', | |
value: 'valuea', | |
next: { | |
key: 'b', | |
value: 'valueb', | |
next: { | |
key: 'c', | |
value: 'valuec' | |
} | |
} | |
} as NestedKeyValuePair | |
// flatten the testing object | |
let flatTests = flatten(tests) | |
// try reverting back the flatten object into the original one | |
let backToOriginal = toNestedKeyValuePair(flatTests) | |
console.log(`Original object: ${JSON.stringify(tests)}`) | |
console.log(`Flattened object: ${JSON.stringify(flatTests)}`) | |
console.log(`Reverted back: ${JSON.stringify(backToOriginal)}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment