Search code examples
javascriptjqueryjsonproperty-files

How to convert config.properties into key value pairs?


I am trying to convert a java properties file into a key value pairs that I can use in jquery. The property file sends information that looks like this:

company1=Google
company2=eBay
company3=Yahoo

And I want it in this form:

var obj = {
 company1: Google,
 company2: ebay,
 company3: Yahoo
};

I am going to be accessing the property file through a URL.


Solution

  • Assuming your file comes exactly the way you've pasted it here, I would approach it something like this:

    var data = "company1=Google\ncompany2=eBay\ncompany3=Yahoo";
    
    var formattedData = data
      // split the data by line
      .split("\n")
      // split each row into key and property
      .map(row => row.split("="))
      // use reduce to assign key-value pairs to a new object
      // using Array.prototype.reduce
      .reduce((acc, [key, value]) => (acc[key] = value, acc), {});
    
    var obj = formattedData;
    
    console.log(obj);

    This post may be helpful if you need to support ES5 Create object from array