admin管理员组

文章数量:1405534

What I'm trying to do is create a object literal on the fly with dynamic properties.

I have an array containing the content (CSV format) of a file.

Each element is one line (the content was split with /\r?\n/).

The first element (first line) of that array contains the parameters I want to have for my object literal, separated by mas.

All the other elements are values (still CSV format) of the parameters set in the first line.

The code I have at the moment is the following :

function jsonDataArray(array) {
    var jsonResult = [],
        parameters = [],
        values;
    for(var i=0; i < array.length; i++) {
        if(i === 0) {
            var parameters = array[i].split(',');
            var objJSON = {};
            for(var k=0; k < parameters.length; k++) {
                objJSON.eval(parameters[k]);
            }
            continue;
        }
        values = array[i].split(',')
        for(var j=0; j < objJSON.length; j++) {
            objJSON[j] = values;
        }
        jsonResult.push(objJSON);
    }
    return jsonResult;
}

Now when I launch this code in node, the objJSON.eval(parameters[k]) line seems to be the one where the problem is, but I wasn't able to solve the problem.

So basically my questions are the following :

  • How should I proceed to have the parameters from the first line set as parameters of a JSON object + fill the values of the other lines in ?

  • Is it safe to parse new lines with this : /\r?\n/ ?

Thank you in advance for your help !

EDIT : I mistakenly used the term JSON to mean object literal so I corrected the question. I didn't modify the function though so that I don't add errors in the code by mistake.

What I'm trying to do is create a object literal on the fly with dynamic properties.

I have an array containing the content (CSV format) of a file.

Each element is one line (the content was split with /\r?\n/).

The first element (first line) of that array contains the parameters I want to have for my object literal, separated by mas.

All the other elements are values (still CSV format) of the parameters set in the first line.

The code I have at the moment is the following :

function jsonDataArray(array) {
    var jsonResult = [],
        parameters = [],
        values;
    for(var i=0; i < array.length; i++) {
        if(i === 0) {
            var parameters = array[i].split(',');
            var objJSON = {};
            for(var k=0; k < parameters.length; k++) {
                objJSON.eval(parameters[k]);
            }
            continue;
        }
        values = array[i].split(',')
        for(var j=0; j < objJSON.length; j++) {
            objJSON[j] = values;
        }
        jsonResult.push(objJSON);
    }
    return jsonResult;
}

Now when I launch this code in node, the objJSON.eval(parameters[k]) line seems to be the one where the problem is, but I wasn't able to solve the problem.

So basically my questions are the following :

  • How should I proceed to have the parameters from the first line set as parameters of a JSON object + fill the values of the other lines in ?

  • Is it safe to parse new lines with this : /\r?\n/ ?

Thank you in advance for your help !

EDIT : I mistakenly used the term JSON to mean object literal so I corrected the question. I didn't modify the function though so that I don't add errors in the code by mistake.

Share Improve this question edited Aug 2, 2012 at 23:10 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Aug 2, 2012 at 22:55 m_vdbeekm_vdbeek 3,7848 gold badges49 silver badges79 bronze badges 4
  • 1 It's not JSON, it is just a javascript object – zerkms Commented Aug 2, 2012 at 22:58
  • Sorry, I misunderstood the term. I edited my question. – m_vdbeek Commented Aug 2, 2012 at 23:02
  • JSON is a string that represents a javascript object. what exactly are you trying to acplish with this line? objJSON.eval(parameters[k]); – dqhendricks Commented Aug 2, 2012 at 23:06
  • I'm trying to create a property for the object 'objJSON'. This property should be named like the value of the element k in array parameters. – m_vdbeek Commented Aug 2, 2012 at 23:08
Add a ment  | 

3 Answers 3

Reset to default 3

It looks to me you want an array of objects, each object having keys from the first row (headers).

The following code assumes you already broke the csv into each line via \r?\n

(function() {
  var csv = [];
      csv.push('name,age,gender');
      csv.push('jake,13,m');
      csv.push('sarah,15,f');
      csv.push('john,18,m');
      csv.push('nick,13,m');

  console.log(csv);

  function jsonDataArray(array) {
    var headers = array[0].split(',');
    var jsonData = [];
    for ( var i = 1, length = array.length; i < length; i++ )
    {
      var row = array[i].split(',');
      var data = {};
      for ( var x = 0; x < row.length; x++ )
      {
        data[headers[x]] = row[x];
      }
      jsonData.push(data);

    }

    return jsonData;
  }

  console.log(jsonDataArray(csv));


})();

http://jsbin./igiwor/2/edit

This will produce something like the follow:

[{ name="jake",  age="13",  gender="m"},
{ name="sarah",  age="15",  gender="f"}, 
{ name="john",  age="18",  gender="m"},
{ name="nick"  age="13",  gender="m"}]

Here is my CSV-parse function, I hope it helps:

function parseCSV(input) {
    var rows = input.split(/\r?\n/);
    var keys = rows.shift().split(",");
    return rows.map(function(row) {
        return row.split(",").reduce(function(map, val, i) {
            map[keys[i]] = val;
            return map;
        }, {});
    });
}

How should I proceed to have the parameters from the first line set as parameters of a JSON object + fill the values of the other lines in?

Just loop through the values. Then, the key as which the values[i] is added to the object is parameters[i]. In my version that is the line map[keys[i]] = val;

Is it safe to parse new lines with this: /\r?\n/?

I think yes.

I think you can just say the following, but I'm not sure what <somevalue> should be.

      objJSON[parameters[k]] = <somevalue>;

In any case, consider the following,

var anObj = {};

anObj["a1"] = "sam";
anObj["a2"] = 5;

This is the same as

var anObj = { a1 : "sam", a2 : 5 };

本文标签: javascriptCreate object on the fly from CSVStack Overflow