我有这样的字符串数组:
"[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}
答案 0 :(得分:9)
使用substring
,split
和reduce
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
<强>演示强>
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;