mardi 4 août 2015

Use Javascript to objectify csv file

I'm currently working with CSV files that I whould like to objectify.

The csv format is like:

 "Property, Value1, Value2, ..." Example: 

 "Recipe_Product_Name, Knife, Fork, Spoon". 

I use the split('_') function to get a JSON looking structure, for the example above:

"Recepie-Product-Name: Knife" gives me a nice,

var name = Recepie.Product.Fork.Name

To the problem...

The csv file includes arrays like:

* "Recipe_Product_Connector{0}_Pins, 11, 47, 4" 
* "Recipe_Product_Connector{0}_Brand, Sourai, Harting, Amphenol"
* "Recipe_Product_Connector{1}_Pins, 5, 64, 18" 
* "Recipe_Product_Connector{1}_Brand, Sourai, Harting, Amphenol"

So far, I use this code for the objectification:

    var nest = function (obj, keys, v) {
    var Arr = [];
    if (keys.length === 1) {
        obj[keys[0]] = v;
    } else {
        var key = keys.shift();
        if (key.split('}').length > 1) {
            Arr.push(nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v));
            obj[key] = Arr;
            console.log(Arr);
        } else {
            obj[key] = nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v);
        }
    }
    return obj;
};

It works kind of good, except that I get multiple array structures:

var HartingPins = Recipe.Products.Connector[0][0].Pins

I do not like that, probably something wrong with the recursion. Any Ideas on how to continue?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire