如何使用javascript将字典列表中的数字字符串转换为整数?

时间:2014-07-31 01:04:20

标签: javascript list dictionary d3.js crossfilter

我有以下词典列表,但问题是每个词典的数量下的值当前是一个字符串。我想在此列表中使用crossfilter,但为了做到这一点,我需要将其转换为整数。

var data = [{
    date: "2011-11-14T16:17:54Z",
    quantity: "2",
    total: 190,
    tip: 100,
    type: "tab"
}, {
    date: "2011-11-14T16:20:19Z",
    quantity: "2",
    total: NaN,
    tip: 100,
    type: "tab"
}, {
    date: "2011-11-14T16:28:54Z",
    quantity: "1",
    total: 300,
    tip: 200,
    type: "visa"
}, {
    date: "2011-11-14T16:30:43Z",
    quantity: "2",
    total: 90,
    tip: 0,
    type: "tab"
}, {
    date: "2011-11-14T16:48:46Z",
    quantity: "2",
    total: 90,
    tip: 0,
    type: "tab"
}, {
    date: "2011-11-14T16:53:41Z",
    quantity: "2",
    total: 90,
    tip: 0,
    type: "tab"
}, {
    date: "2011-11-14T16:54:06Z",
    quantity: "1",
    total: NaN,
    tip: null,
    type: "cash"
}, {
    date: "2011-11-14T17:02:03Z",
    quantity: "2",
    total: 90,
    tip: 0,
    type: "tab"
}, {
    date: "2011-11-14T17:07:21Z",
    quantity: "2",
    total: 90,
    tip: 0,
    type: "tab"
}, {
    date: "2011-11-14T17:22:59Z",
    quantity: "2",
    total: 90,
    tip: 0,
    type: "tab"
}, {
    date: "2011-11-14T17:25:45Z",
    quantity: "2",
    total: 200,
    tip: null,
    type: "cash"
}, {
    date: "2011-11-14T17:29:52Z",
    quantity: "1",
    total: 200,
    tip: 100,
    type: "visa"
}];

这是我想做的事情。

data.forEach(function(d) {
    d.quantity = d.parseInt(d.quantity,10);
});

1 个答案:

答案 0 :(得分:2)

修复代码:

data.forEach(function(d) {
    d.quantity = parseInt(d.quantity,10);
});

OR

data.forEach(function(d) {
    d.quantity = +d.quantity;
});