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

DHA*_*NGH 0 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]"
Run Code Online (Sandbox Code Playgroud)

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

{totRev:'248634.29858677526',....etc} 
Run Code Online (Sandbox Code Playgroud)

gur*_*372 9

使用substring,splitreduce

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 ) , {} );
Run Code Online (Sandbox Code Playgroud)

减少解释

  • 拆分 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);
Run Code Online (Sandbox Code Playgroud)