如何重组json数据?

时间:2017-05-12 22:19:32

标签: javascript php jquery json

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

所以现在我有:

[  
   {  
      "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完成的。 这是表单的图像,如果它有帮助:enter image description here

更新的 以下是我正在做的改变可能更好的方法:

$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
    ]);
}

使用eloquent将数组插入db。

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

2 个答案:

答案 0 :(得分:0)

使用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);




答案 1 :(得分:-2)

function test()
{
//alert("Hi");
var text = '[{"name":"email8","value":"admin@e17pumphouse.org.uk"},{"name":"password8","value":"pass"},{"name":"email9","value":"hireing@e17pumphouse.org.uk"},{"name":"password9","value":"pass"},{"name":"email10","value":"abdullah.seba@e17pumphouse.org.uk"},{"name":"password10","value":"pass"}]'

json = JSON.parse(text);

var result = {};

for(var i = 0; i < json.length; i++) {
    var obj = json[i];

    if(obj.name.startsWith('email')){
        key = obj.value;
      i++;
      var obj = json[i];
      if(obj.name.startsWith('password')){
        result[key] = obj.value;
      }
    }


}

console.log(result);

}