0

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  }
3
  • Can you provide an example of the data stored in the csv, and the expected output for that example? Commented Oct 6, 2018 at 17:04
  • 1
    newItem["Column with spaces 1"] = parseInt(item["Column with spaces 1"]) and the same for the other property. Commented Oct 6, 2018 at 17:11
  • 1
    for a more dynamic way: Object.keys(item).forEach(key => newItem[key] = +item[key]). It handles all the keys. Commented Oct 6, 2018 at 17:12

1 Answer 1

1

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

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.