Reputation: 4928
right now after loading csv file I am looping each object within an array and converting one by one.
which looks like
fulldata.forEach(function(data){
data.healthcare = +data.healthcare;
data.a = +data.a;
data.b = +data.b;
data.c = +data.c;
})
assume there are about 100 feature that you need to convert into number, is there a way that convert multiple feature into number at once?
Upvotes: 2
Views: 3147
Reputation: 102219
D3 v5 introduced a very convenient method, called d3.autoType
, which:
For each value in the given object, the trimmed value is computed; the value is then re-assigned as follows:
- If empty, then
null
.- If exactly "true", then
true
.- If exactly "false", then
false
.- If exactly "NaN", then
NaN
.- Otherwise, if coercible to a number, then a number.
- Otherwise, if a date-only or date-time string, then a Date.
- Otherwise, a string (the original untrimmed value).
It is very handy when you don't have all columns as a numeric value. For instance, using d3.csvParse
, you just need:
const fullData = d3.csvParse("your_CSV_URL_here", d3.autoType);
Here is a demo:
const csv = `number,string,date
32,foo,2019-01-21
47,bar,2018-11-19
17,baz,2019-07-28`;
const data = d3.csvParse(csv, d3.autoType);
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.0/d3.min.js"></script>
However, if in fact you have all columns as numeric values, just get all properties inside the row
function:
const csv = `foo,bar,baz
12,43,23
75,44,32
76,93,23`;
const data = d3.csvParse(csv, function(d) {
d3.keys(d).forEach(function(e) {
d[e] = +d[e]
})
return d;
});
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Upvotes: 4
Reputation: 1571
You can use Object.keys()
to get an array of features.
fulldata.forEach(function(data) {
Object.keys(data).forEach(function(key) {
data[key] = +data.key;
});
})
Upvotes: 0