我有一个从 html 表单收到的对象,它具有以下语法:
'ingredients[0][name]': 'eggplant',
'ingredients[0][mass]': '1',
'ingredients[0][units]': 'pc',
'ingredients[1][name]': 'cheese',
'ingredients[1][mass]': '150',
'ingredients[1][units]': 'gr',
'ingredients[2][name]': 'cilantro',
'ingredients[2][mass]': '100',
'ingredients[2][units]': 'tt' ...
我所需要的就是将这些键值对转换为一个大对象字段。比如
recipe = {
ingredients: [
{
name: 'epplant',
mass: '1',
units: 'pc'
},
{
name: 'cheese',
mass: '150',
units: 'gr'
}, ...
]
}
如果没有 JQuery 或其他 JS 框架,我该如何做到这一点?
最佳答案
var form = {
'ingredients[0][name]': 'eggplant',
'ingredients[0][mass]': '1',
'ingredients[0][units]': 'pc',
'ingredients[1][name]': 'cheese',
'ingredients[1][mass]': '150',
'ingredients[1][units]': 'gr',
'ingredients[2][name]': 'cilantro',
'ingredients[2][mass]': '100',
'ingredients[2][units]': 'tt'
}
var re = /([a-zA-Z][a-zA-Z_0-9]*)\[(\d+)\]\[([a-zA-Z][a-zA-Z0-9_]*)\]/
var result = {}
for (var key in form) {
var match = key.match(re)
if (!match) continue
var arr = result[match[1]]
if (!arr) arr = result[match[1]] = []
var obj = arr[match[2]]
if (!obj) obj = arr[match[2]] = {}
obj[match[3]] = form[key]
}
console.log(result)
UPD:一些解释:
我认为,您应该迭代抛出输入表单对象键并使用正则表达式解析它。如果匹配,您可以构建所需的输出结构
关于javascript - 将键值对转换为数组javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349552/