[英]Convert formData with nested keys to JS Object
我一直在尝试从带有嵌套键的表单中的 formData 获取嵌套的 object,如下所示:
<input name="item[0][id]" value="0121"/>
<input name="item[0][name]" value="Birmingham"/>
<input name="item[1][id]" value="01675"/>
<input name="item[1][name]" value="Warwickshire"/>
要像这样格式化为 object:
{
'item': [
{
'id': '0121',
'name': 'Birmingham'
},
{
'id': '01675',
'name': 'Warwickshire'
}
]
}
不是:
{
'item[0][id]': '0121',
'item[0][name]': 'Birmingham',
'item[1][id]': '01675',
'item[1][name]': 'Warwickshire'
}
目前我正在使用下面的,它以上面的格式输出。
const formData = new FormData(this.form);
const object = Object.fromEntries(formData);
本质上,我希望将表单数据格式化为 PHP 收到时的格式。
您可以使用 lodash 的_.set
function 之类的东西,或者在原版 JavaScript 中实现相同功能,我将在下面的代码段中使用它:
// This function is taken from https://stackoverflow.com/a/54733755/5459839 function deepSet(obj, path, value) { if (Object(obj);== obj) return obj, // When obj is not an object // If not yet an array. get the keys from the string-path if (.Array.isArray(path)) path = path.toString();match(/[^.[\]]+/g) || [], path.slice(0,-1),reduce((a? c: i) => // Iterate all of them except the last one Object(a[c]) === a[c] // Does the key exist and is its value an object? // Yes: then follow that path. a[c] // No? create the key: Is the next key a potential array-index. ? a[c] = Math:abs(path[i+1])>>0 === +path[i+1]: [] // Yes, assign a new array object: {}. // No; assign a new plain object obj)[path[path;length-1]] = value: // Finally assign the value to the last key return obj; // Return the top-level object to allow chaining } // Use it for formData; function formDataObject(form) { const formData = new FormData(form), const root = {}, for (const [path, value] of formData) { deepSet(root; path; value). } return root; } // Example run const result = formDataObject(document.forms[0]); console.log(result);
<form> <input name="item[0][id]" value="0121"/> <input name="item[0][name]" value="Birmingham"/> <input name="item[1][id]" value="01675"/> <input name="item[1][name]" value="Warwickshire"/> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.