I am new to Javascript and am having trouble parsing a file with INI formatting into nested objects.
The file that I have is formatted as follows:
ford.car.focus.transmission=standard
ford.car.focus.engine=four-cylinder
ford.car.focus.fuel=gas
ford.car.taurus.transmission=automatic
ford.car.taurus.engine=V-8
ford.car.taurus.fuel=diesel
purchased=Ford Taurus
I would like the structure to look like this:
{ ford:
{ car:
{ focus:
{
transmission: 'standard',
engine: 'four-cylinder',
fuel: 'gas'
}
}
{ taurus:
{
transmission: 'automatic',
engine: 'V-8',
fuel: 'diesel'
}
}
}
purchased: 'Ford Taurus'
}
I store the file in lines in an array, splitting into '\ n'. I am trying to write a method that will be called in a loop, passing my global object as follows:
var hash = {};
var array = fileData.toString().split("\n");
for (i in array) {
var tmp = array[i].split("=");
createNestedObjects(tmp[0], tmp[1], hash);
}
This should allow me to access the values ββin the hash object, for example:
hash.ford.car.focus.fuel
# 'gas'
hash.purchase
# 'Ford Taurus'
I tried something like what was suggested here: Javascript: how to dynamically create nested objects using the object names given by the array , but this only seems to set the last element in the socket.
{ fuel: 'diesel',
purchased: 'Ford Taurus' }
My unsuccessful attempt looks like this:
createNestedObjects(path, value, obj) {
var keys = path.split('.');
keys.reduce(function(o, k) {
if (k == keys[keys.length-1]) {
return o[k] = value;
} else {
return o[k] = {};
}
}, obj);
}
:
{ ford: { car: { taurus: { fuel: 'diesel' } } },
purchased: 'Ford Taurus' }