2

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

2
  • I don't understand what you want it to do that it isn't already doing. You end up with an array of objects, each one corresponding to a row; how is that not good enough? Did you want an object holding objects instead? Could you show us the code you tried that didn't work? Commented Oct 21, 2011 at 21:50
  • Do you mean for dataProvider to be a global variable rather than declaring it locally and then returning it from the parseCSV() function? Commented Oct 21, 2011 at 22:05

2 Answers 2

4

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};
Sign up to request clarification or add additional context in comments.

2 Comments

And don't forget simply hash.myNewValue = 42;
hash should be created anyway before. using variables before declaring em is a bad practice.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.