jbmoon jbmoon - 7 months ago 16
Javascript Question

Node.js - Javascript - Parsing file into nested objects

I'm new to Javascript and am having trouble with a function I wrote. I'm using array.reduce() to do the job, but it is failing on Windows (testing on Mac works fine).

The file I have is formatted like this:

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 to have the structure 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'm storing file lines in an array, splitting on '\n'. I'm trying to write a method that would be called in a loop, passing my global object like this:

var hash = {};
var array = fileData.toString().split("\n");
for (i in array) {
var tmp = array[i].split("=");
createNestedObjects(tmp[0], tmp[1], hash);
}


My current function looks like this:

function create_nested_object(path, value, obj) {
var keys = path.split('.');
keys.reduce(function(o, k) {
if (k == keys[keys.length-1]) {
return o[k] = value;
} else if (o[k]) {
return o[k];
} else {
return o[k] = {};
}
}, obj);
}


I would like to turn this into a for loop. I have new code that looks like this (I tried converting the array.reduce() code):

function create_nested_object(path, value, obj) {
var keys = path.split('.');

for (var i = 0; i < keys.length; i++) {
if (keys[i] == keys[keys.length-1]) {
obj[keys[i]] = value;
} else if (obj[keys[i]] == keys[i]) {
obj;
} else {
obj = obj[keys[i]] = {};
}
}
}


But it only returns the last items in each nest:

{
"ford": {
"car": {
"taurus": {
"fuel": "diesel"
}
}
},
"purchased": "Ford Taurus"
}


I know I'm missing something, but I can't figure out what's wrong. Any help would be appreciated!

Related question: Javascript - Parsing INI file into nested associative array

Answer

EDIT to use os.EOL

solution in the comments: In the OP code:

var array = fileData.toString().split("\n");

And, as @Marty suggested, Needs to be:

var array = fileData.toString().split(os.EOL);

In Windows.