Radoslaw
Radoslaw

Reputation: 171

Javascript dynamic hash creation

here is my working function. How to create dataObject dynamically? (let's assume that I know how many columns I have) I tried dynamically create variables 'value+i' with eval function, but with no success.

    function parseCSV(rows){
        dataProvider = [];
        for (var i = 0; i < rows.length; i++){
            if (rows[i]) {                   
                var column = rows[i].split(","); 
                var date = someFunction(column[0]);
                var value1 = column[1];
                var value2 = column[2];
                var dataObject = {date:date, value1:value1, value2:value2};
                dataProvider.push(dataObject);
            }
        }
    }

thank U

Upvotes: 2

Views: 3388

Answers (2)

Zack Bloom
Zack Bloom

Reputation: 8427

If you don't know how many columns you have, but want to create an object full of valueX's:

var date = someFunction(column[0]);
var dataObject = {date: date};

for (var i=1; i < column.length; i++){
    dataObject['value' + i] = column[i];
}

Rather than using value1, ... you should try to use more descriptive names, if possible.

Upvotes: 0

mephisto123
mephisto123

Reputation: 1448

There are few approaches.

First:

var hash = new object();
hash["date"] = date;
hash["value1"] = value1;
hash["value2"] = value2;

Second:

var hash = {};
hash["date"] = date;
hash["value1"] = value1;
hash["value2"] = value2;

Third:

var hash = {"date" : date, "value1" : value1, "value2" : value2};

Upvotes: 4

Related Questions