2017-05-12 60 views
-1

我如何重組形式的數據通過serializeArray() 返回到更理想的結構?如何重構表單json數據?

所以現在我有:

[ 
    { 
     "name":"email8", 
     "value":"[email protected]" 
    }, 
    { 
     "name":"password8", 
     "value":"pass1" 
    }, 
    { 
     "name":"email9", 
     "value":"[email protected]" 
    }, 
    { 
     "name":"password9", 
     "value":"pass2" 
    }, 
    { 
     "name":"email10", 
     "value":"[email protected]" 
    }, 
    { 
     "name":"password10", 
     "value":"pass3" 
    } 
] 

我希望它是:

{ 
    "[email protected]":"pass1", 
    "[email protected]":"pass2", 
    "[email protected]":"pass3" 
} 

我不介意,如果這是在PHP或Javascript來完成。 這裏是形式的圖像,如果有幫助:enter image description here

更新: 這是我在做什麼,可能是更好的改變:

$user = WebmailAutologinUser::find(1); 
$emails = array(
"[email protected]" => "pass1", 
"[email protected]" => "pass2", 
"[email protected]" => "pass3"); 

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

其使用雄辯地內陷式數組進入數據庫。

所以emailpassword在DB列。

+0

寫自定義序列? –

回答

0

可行的方法,使用Array#reduce

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

 
    console.log(res);

+0

如果你不得不問,如果你的答案是正確的,也許等待發布之前? –

+0

@SterlingArcher這是真的很糟糕,我問OP是否正是他想要的?等待他的迴應,刪除/改進我的答案。無論如何,像你這樣的行爲目前沒有任何幫助。相當具有破壞性。 –

+0

關閉但返回 ''' { 「email8」: 「[email protected]」, 「password8」: 「通行證」, 「email9」: 「[email protected]」 「password9」: 「通行證」, 「email10」: 「[email protected]」, 「password10」: 「通」 } ''' –

-2
function test() 
{ 
//alert("Hi"); 
var text = '[{"name":"email8","value":"[email protected]"},{"name":"password8","value":"pass"},{"name":"email9","value":"[email protected]"},{"name":"password9","value":"pass"},{"name":"email10","value":"[email protected]"},{"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); 

}