Slava32 Slava32 - 6 months ago 21
Javascript Question

new array from csv data

I have the following csv data:

id,v1,v2,v3,v4,v5
Lo,32,45,37,53,22


I want to create new array which looks this way:

id2,value
v1,32
v2,45
v3,37
v4,53
v5,22


To do it I use the following code:

d3.csv("dataSBar1.csv", function(error, data) {
if (error) throw error;

var values = d3.keys(data[0]).filter(function(key) {
return key !== "id";});

data.forEach(function(d) {
for (var i = 0; i <= values.length; i++) {
d.value = +d[values[i]];
return d;}});

/*---------- create new array ----------*/

var array = $.map(data, function (d) {
for( var i=0; i<=values.length; i++){
return {
id2: values[i],
value: d[values[i]]
}
}
});


It returns me only

0: Object
id2: "v1"
value: "32"


and nothing more.
What am I doing wrong?

Thanks in advance!

Answer

Don't need so many for loops simply do as below:

d3.csv("my.csv", function(error, data) {
  if (error) throw error;

  //get all values without id    
  var values = d3.keys(data[0]).filter(function(key) {
    return key !== "id";
  });
  //iterate through the values and get the value using map.
  var id2 = values.map(function(id, index) {
    return {
      "id2": id,
      "value": +data[0][id]
    };

  });
  console.log(id2)
});

working code here

Comments