如何在Javascript中将字符串数组转换为JSON数组?

时间:2017-12-08 05:48:15

标签: javascript json

我有这样的字符串数组:

"[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]"

如何将其转换为JSON数组或JSON对象(如

{totRev:'248634.29858677526',....etc} 

1 个答案:

答案 0 :(得分:9)

使用substringsplitreduce

str.substring( 1,str.length - 1 ) //remove [ and ] from the string
    .split(",") //split by ,
    .reduce( (a,b) => (i = b.split("="), a[i[0]] = i[1], a ) , {} );

减少解释

  • 拆分 b(数组中的元素,例如totRev=248634.29858677526=
  • 分配数组中的第一项作为a的关键字(累加器初始化为{}),值为数组的第二项
  • 返回 a

<强>演示

&#13;
&#13;
var str = "[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]";
var output = str.substring(1,str.length-1).split(",").reduce( (a,b) => (i = b.split("="), a[i[0].trim()] = i[1], a ) , {} );
console.log(output);
&#13;
&#13;
&#13;