如何重组表格json数据? [英] How to restructure form json data?

查看:101
本文介绍了如何重组表格json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重组serializeArray()返回的表单数据 到更理想的结构?

How can I restructure form data returned by serializeArray() to a more desirable structure?

现在我有:

[  
   {  
      "name":"email8",
      "value":"test1@test.com"
   },
   {  
      "name":"password8",
      "value":"pass1"
   },
   {  
      "name":"email9",
      "value":"test2@test.com"
   },
   {  
      "name":"password9",
      "value":"pass2"
   },
   {  
      "name":"email10",
      "value":"test2@test.com"
   },
   {  
      "name":"password10",
      "value":"pass3"
   }
]

我希望它是

{  
   "test1@test.com":"pass1",
   "test2@test.com":"pass2",
   "test3@test.com":"pass3"
}

我不介意这是用PHP还是Javascript完成的. 这是表单的图像,如果有帮助的话:

I dont mind if this is done in PHP or Javascript. Here Is an image of the form if it helps:

更新: 这是我正在做的,最好更改一下:

Update: Here is what I'm doing that might be better to change:

$user = WebmailAutologinUser::find(1);
$emails = array(
"test1@test.com" => "pass1",
"test2@test.com" => "pass2",
"test3@test.com" => "pass3" );

foreach ($emails as $email => $password) {
    $user->autoLoginAccounts()->create([
        'email' => $email,
        'password' => $password
    ]);
}

使用雄辩的方法将数组插入db中.

Its using eloquent to inset the array into the db.

所以emailpassword是数据库中的一列.

So email and password is a column in the db.

推荐答案

可能的方法,使用Array#reduce.

var arr = [{"name":"email8","value":"test1@test.com"},{"name":"password8","value":"pass1"},{"name":"email9","value":"test2@test.com"},{"name":"password9","value":"pass2"},{"name":"email10","value":"test3@test.com"},{"name":"password10","value":"pass3"}],
    res = arr.reduce((s,a,i) => (i % 2 ? s[arr[i-1].value] = a.value : null, s), {});

    console.log(res);

这篇关于如何重组表格json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆