【问题标题】:Javascript d3 object string to numberJavascript d3对象字符串到数字
【发布时间】:2018-10-06 16:56:12
【问题描述】:

我有一个 csv,我试图将某些数据转换为整数,当我解析它仍然作为字符串显示在控制台中的对象时。

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.

当我 console.log 时,数据存储在一个看起来像这样的对象中

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

我想把它转换成数字而不是字符串

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

【问题讨论】:

  • 您能否提供一个存储在 csv 中的数据示例,以及该示例的预期输出?
  • newItem["Column with spaces 1"] = parseInt(item["Column with spaces 1"]) 和其他属性相同。
  • 获取更动态的方式:Object.keys(item).forEach(key => newItem[key] = +item[key])。它处理所有的键。

标签: javascript d3.js type-conversion


【解决方案1】:

通过将unary operator + 添加到 item 的值来将其转换为数字就足够了,例如:

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

【讨论】:

    猜你喜欢
    • 2012-10-11
    • 2017-08-27
    • 2021-08-08
    • 2020-06-18
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2013-03-29
    • 2013-04-21
    相关资源
    最近更新 更多