0

I have string array like this:

"[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]"

How do I convert this either into a JSON Array or a JSON object like

{totRev:'248634.29858677526',....etc} 
8
  • one word .. do it carefully ... note, your expected "Object" is not valid JS ... seems like you want the object to be like {totRev: 248634.29858677526, totEBITDA: 34904.9893085068, ...} or, as JSON, {"totRev": 248634.29858677526, "totEBITDA": 34904.9893085068, ...} - oh, and there's no such thing as a JSON array - unless you are referring to an array of JSON strings, which is not relevant to this at all Commented Dec 8, 2017 at 5:50
  • str.split(', ').reduce((p,c) => { const parts = c.split('='); p[parts[0] = [arts[1]; return p;]}, {}) Commented Dec 8, 2017 at 5:51
  • Sorry for my mistake actually want in json object like {totRev:248634.29858677526,....} Commented Dec 8, 2017 at 5:52
  • no such thing as a JSON object either - JSON is a STRING representation of a javascript object, but it isn't an object Commented Dec 8, 2017 at 5:54
  • 1
    @DHARMENDRASINGH There is a typo. Please read the code before using it. :-p = [arts[1] should be = parts[1] Commented Dec 8, 2017 at 5:56

1 Answer 1

9

Use substring, split and 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 ) , {} );

Reduce explanation

  • Split b (element in the array such as totRev=248634.29858677526) by =
  • Assign the first item in the array as key to a (accumulator initialized as {}) and value as second item of the array
  • Return a

Demo

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);

2
  • @guruvinder372, can you explain this part .reduce( (a,b) => (i = b.split("="), a[i[0]] = i[1], a ) , {} ) ? Commented Dec 8, 2017 at 5:58
  • 1
    @guruvinder372 its a great and optimised solution. Commented Dec 8, 2017 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.