3

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.

Mandalina
  • 446
  • 5
  • 22

2 Answers2

6

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

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
FranCarstens
  • 1,203
  • 8
  • 13
  • 2
    Good answer +1. Note that your reduce could be rewritten as `.reduce((acc, [key, value]) => (acc[key] = value, acc), {});` which is both shorter and faster since it doesn't re-allocate the accumulator each step through the loop. – Jared Smith Aug 27 '18 at 17:14
  • Thank you so much! This is exactly what I was looking for – Mandalina Aug 27 '18 at 17:16
1

Just use npm module https://www.npmjs.com/package/properties

This module implements the Java .properties specification and adds additional features like ini sections, variables (key referencing), namespaces, importing files and much more.

# file
compa = 1
compb = 2


nodejs:

var properties = require ("properties");

properties.parse ("file.properties", { path: true }, function (error, obj){
  if (error) return console.error (error);

  console.log (obj);
  //{ compa : 1, compb : 2 }
});
аlex
  • 5,426
  • 1
  • 29
  • 38
  • Thank you for your response. However for this project I was hoping for something to just parse the data. Completely done in the front end – Mandalina Aug 27 '18 at 16:05
  • While it's frequently a good idea to use battle-tested third party libraries instead of rolling your own, for something this trivial it probably isn't worth taking on a dependency (insert left-pad joke here) :) – Jared Smith Aug 27 '18 at 17:16