-1

I got a requirement to convert .properties file to JSON object using angular js.

I have no clue how to achive this, i searched in net but did not found the solution. Could you please help me with this.

.properties file contains

a.b.10=M
a.b.11=M50
a.b.12=M508

Output should be

{"a":{"b":{"10":"M","11":"M50","12":"M508"}}}
Rjj
  • 249
  • 1
  • 7
  • 22

1 Answers1

2

Try this

var str1 = "a.b.12=M508";
var str2 = "a.b.10=M";
var str3 = "a.b.11=M50";
var result = {};

function createObject(str) {
    str.split('.').reduce((obj, key) => {
        if (!obj[key] && !key.includes('='))
            obj[key] = {};
        else if (key.includes('=')) {
            var keys = key.split('=');
            obj[keys[0]] = keys[1];
        }
        return obj[key];
    }, result);
    return result;
}
createObject(str1);
createObject(str2);
createObject(str3);
console.log(result);
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
  • Thanks for your quick reply!!! however in this eg we have 3 key value pair. what if the properties file is appended with few more values. does that also require code update? – Rjj Feb 21 '18 at 16:56