Created
May 25, 2023 20:40
-
-
Save cjavdev/0254d3c6f71661982fb5af26d8892046 to your computer and use it in GitHub Desktop.
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
// TODO: Make typescript happy here. | |
type JSONValue = | |
| string | |
| number | |
| boolean | |
| { [x: string]: JSONValue } | |
| Array<JSONValue>; | |
interface JSONObject { | |
[x: string]: JSONValue; | |
} | |
type JSONArray = Array<JSONValue>; | |
function update( | |
data: JSONObject, | |
keys: string[], | |
value: JSONArray | JSONObject | JSONValue, | |
) { | |
if (keys.length === 0) { | |
// Leaf node | |
return value; | |
} | |
let key = keys.shift(); | |
if (!key) { | |
data = data || []; | |
if (Array.isArray(data)) { | |
key = data.length; | |
} | |
} | |
// Try converting key to a numeric value | |
const index = +key; | |
if (!isNaN(index)) { | |
// We have a numeric index, make data a numeric array | |
// This will not work if this is a associative array | |
// with numeric keys | |
data = data || []; | |
key = index; | |
} | |
// If none of the above matched, we have an associative array | |
data = data || {}; | |
const val = update(data[key], keys, value); | |
data[key] = val; | |
return data; | |
} | |
export const deserialize = (formData: FormData) => { | |
return Array.from(formData.entries()).reduce((data, [field, value]) => { | |
console.log({ data }); | |
const matchResult: RegExpMatchArray = field.match( | |
/^([^\[]+)((?:\[[^\]]*\])*)/, | |
); | |
let [_, prefix, keys] = matchResult; | |
if (keys) { | |
keys = Array.from(keys.matchAll(/\[([^\]]*)\]/g), (m) => m[1]); | |
value = update(data[prefix], keys, value); | |
} | |
data[prefix] = value; | |
return data; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment