我从HTML表单中获取VueJS函数调用的表单元素。我创建了一个JSON,如:
var elements = event.target.elements;
var form_elements = [];
for (var i = 0; i < elements.length; i++) {
var element = {};
element[elements[i].getAttribute('name')] = elements[i].value;
form_elements.push(element);
}
form_elements = JSON.stringify(form_elements);
我得到的JSON如下:
var form_elements = [{'name':'John'},{'age':'20'},{'gender':'Male'},];
我想将其转换为:
var form_elements = {'name':'John','age':'20','gender':'Male'};
用于ajax调用。怎么做?
答案 0 :(得分:3)
使用Array.reduce()
将元素组合到单个对象:
var elements = event.target.elements;
var form_elements = elements.reduce(function(r, el) {
r[el.getAttribute('name')] = el.value;
return r;
}, {});
答案 1 :(得分:2)
for
块中的临时变量在您的情况下是无用的,最终代码可能如下所示:
var elements = event.target.elements;
var form_elements = {};
for (var i = 0; i < elements.length; i++) {
form_elements[elements[i].getAttribute('name')] = elements[i].value;
}
并且最终需要form_elements
,尝试JSON.stringify
。
答案 2 :(得分:0)
试试这个:
var form_elements = [{'name':'John'},{'age':'20'},{'gender':'Male'}];
var obj = {};
for (var i in form_elements) {
obj[Object.keys(form_elements[i])[0]] = form_elements[i][Object.keys(form_elements[i])[0]];
}
console.log(obj); // {name: "John", age: "20", gender: "Male"}