我正在使用jquery验证插件处理某些表格
现在我正尝试将表单值发送到服务器,但是我需要将其信息以JSON格式发送..因此,在我的SubmitHandler方法中,我正在这样做...
var formData = JSON.stringify($("#form").serializeArray());
但是现在这个变量formData包含了它。
[ { name: 'nombre', value: 'ffgsdfgdfs' },
{ name: 'apellidos', value: 'gsdfgsdfg' },
{ name: 'email', value: 'dsfgg@gkfgd.com' },
{ name: 'usuario', value: 'fgsd' },
{ name: 'password', value: 'dksmfklsdm43' },
{ name: 'empresa', value: 'fkdmflksdmfkl' },
{ name: 'cif', value: 'mkfsdmfklsdmfkl' },
{ name: 'telefono', value: 'mfklsdmfklmsdfkl' },
{ name: 'direccion', value: 'mfklsdfmsdklfm' },
{ name: 'pais', value: 'klfmsdklfmsdklmf' },
{ name: 'localidad', value: 'kfmsdklfmsdklfm' },
{ name: 'cp', value: 'kfmsdklfmsdklfml' },
{ name: 'dominio', value: 'sde' },
{ name: 'termino', value: 'on' } ]
但这不是我需要的格式,我需要类似...
formData ={
nombre: 'ffgsdfgdfs',
apellidos: 'gsdfgsdfg' ,
email: 'dsfgg@gkfgd.com' ,
usuario: 'fgsd',
//.... etc etc
} //this is what i would like to have
我该怎么做?我一直在尝试...。但是我无法获得我期望的结果
答案 0 :(得分:4)
您可以映射新对象并将所有对象分配给一个对象。
var data = [{ name: 'nombre', value: 'ffgsdfgdfs' }, { name: 'apellidos', value: 'gsdfgsdfg' }, { name: 'email', value: 'dsfgg@gkfgd.com' }, { name: 'usuario', value: 'fgsd' }, { name: 'password', value: 'dksmfklsdm43' }, { name: 'empresa', value: 'fkdmflksdmfkl' }, { name: 'cif', value: 'mkfsdmfklsdmfkl' }, { name: 'telefono', value: 'mfklsdmfklmsdfkl' }, { name: 'direccion', value: 'mfklsdfmsdklfm' }, { name: 'pais', value: 'klfmsdklfmsdklmf' }, { name: 'localidad', value: 'kfmsdklfmsdklfm' }, { name: 'cp', value: 'kfmsdklfmsdklfml' }, { name: 'dominio', value: 'sde' }, { name: 'termino', value: 'on' }],
result = Object.assign({}, ...data.map(({ name, value }) => ({ [name]: value })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
另一种替代方法是使用Array.reduce(),例如:
const input = [
{name: 'nombre', value: 'foo'},
{name: 'apellidos', value: 'bar bar'},
{name: 'email', value: 'foo@bar.com'},
{name: 'usuario', value: 'foobar'}
];
let res = input.reduce((acc, {name, value}) => (acc[name] = value, acc), {});
console.log("Result is:", res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 2 :(得分:1)
var data = [{ name: 'nombre', value: 'ffgsdfgdfs' },
{ name: 'apellidos', value: 'gsdfgsdfg' },
{ name: 'email', value: 'dsfgg@gkfgd.com' },
{ name: 'usuario', value: 'fgsd' }];
var jsonData = {};
for (var i = 0; i < data.length; i++) {
jsonData[data[i].name] = data[i].value
}