简体   繁体   中英

Javascript d3 object string to number

I have a csv and i am trying to convert certain data to integers when i parse the object it is still showing up in the console as a string.

d3.csv('somecsv.csv' function(response){
  var data = response.map(function(item){
    var newItem{};
    newItem[parseInt("Column with spaces 1")] = item["Column with spaces 1"];
// This gives a Nan error
// even when i do 
//   newItem["Column with spaces 1"] = item["Column with spaces 1"];
//   parseInt(newItem["Column with spaces 1"])
   console.log(newItem)
//  This displays a string. It never converted to an Int.

When i console.log the data is stored in an object that looks like this

Object { "Column with spaces 1": "99", "Column with spaces 2": "37"  }

I want to convert it so it the value is a number not string

Object { "Column with spaces 1": 99, "Column with spaces 2": 37  }

It should be enough to convert it to number by adding unary operator + to the value of item, so something like:

d3.csv('somecsv.csv', function(data) {
  const cleanData = data.map((d) => ({
     ...d,
     fieldNameWithNumber: +d[fieldNameWithNumber]
  });
});  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM