2017-05-31 197 views
-7

我喜歡下面的字符串在JavaScript字符串轉換爲對象

"\nStructure=xyz\nIds=123,456,678,235" 

轉換爲對象

{ 
    "Structure": "xyz", 
    "Id": "123,456,678,235" 
} 

什麼是最好的方法是什麼?

+2

要告訴你的最佳方式,我們需要你嘗試所以我們可以比較它 – Rajesh

+0

轉換成json –

+1

請參閱[**我如何問一個好問題**](https://stackoverflow.com/help/how-to-ask)和[**如何創建一個最小,完整和可驗證的例子**](h ttps://stackoverflow.com/help/mcve)簡單地問:「最好的方式是什麼?」主要是基於意見的。 – Nope

回答

1

嘗試與分隔符\n並用於Array#forEach方法用於分割字符串split()遍歷數組分割字符串後

var a="\nStructure=xyz\nIds=123,456,678,235"; 
 
var one = a.trim().split('\n'); 
 
var res ={}; 
 
one.forEach(a=> res[a.split('=')[0]]=a.split('=')[1]) 
 
//one.forEach(function(a){ res[a.split('=')[0]]=a.split('=')[1]}) for IE or unsupported Arrow function 
 
console.log(res)

+0

用IE運行'function(a){}',因爲'(a)=>'不支持 – NightKn8