UNPKG

@uppercod/form-tools

Version:
48 lines (47 loc) 1.65 kB
// src/module.js function Value(value) { this.value = value; } var getPath = (path) => path.match(/(\[\d+\]|\w+)/g); var createObjectFromPath = (path, value) => path.reverse().reduce((value2, prop) => [prop, value2], new Value(value)); function extend(parent, [name, value]) { if (value instanceof Value) { parent[name] = value.value; } else { const [nextName, nextValue] = value; const test = nextName.match(/^\[(\d+)\]$/); let current = parent[name]; if (test) { const [, index] = test; value = [index, nextValue]; } if (current == null) { current = test ? [] : {}; extend(current, value); } else { extend(current, value); } parent[name] = test ? current.filter((value2) => value2) : current; } return parent; } var getValueFromInput = (name, input) => { const isRadioList = input instanceof RadioNodeList; const withvalue = isRadioList ? true : input.hasAttribute("value"); const { type, value, checked } = input; const isSwitch = type == "radio" || type == "checkbox"; const isNumber = type == "number"; return isSwitch ? withvalue ? checked ? value : null : checked : isRadioList && value === "" ? null : isNumber ? Number(value) : value; }; var formToObject = (defaultData) => (target) => { const elements = Object.entries(target.elements).filter(([prop]) => !/^\d+$/.test(prop)); const data = elements.reduce((data2, [name, input]) => extend(data2, createObjectFromPath(getPath(name), getValueFromInput(name, input))), { ...defaultData }); return data; }; export { createObjectFromPath, extend, formToObject, getPath, getValueFromInput };