1

I have the following data structure:

    const data = [
     {a: '12.03', b: '2.45', c: '24.12'},
     {a: '12.03', b: '22.45', c: '44.12'},
     {a: '15.03', b: '12.45', c: '24.12'},
     .
     .
     .
     n
    ]

And I want to convert the string into a float:

const data = [
     {a: 12.03, b: 2.45, c: 24.12},
     {a: 12.03, b: 22.45, c: 44.12},
     {a: 15.03, b: 12.45, c: 24.12}
    ]

Any Idea on how to iterate over the object and just apply the format so I can use the data array in a line chart?

Emmanuel
  • 2,957
  • 3
  • 14
  • 17
  • Simplest is the unary `+` operator: `data.forEach(obj => Object.keys(obj).forEach(key=>obj[key]=+obj[key])); `. – RobG Oct 08 '18 at 22:25

7 Answers7

5
 data = data.map(({ a, b, c }) => ({ a: parseFloat(a), b: parseFloat(b), c: parseFloat(c) }));

or more general:

 data = data.map(entry => 
   Object.entries(entry).reduce(
       (obj, [key, value]) => (obj[key] = parseFloat(value), obj), 
       {}
   )
 );
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

Everyone seems to want to use parseFloat, but I personally think it's just as readable, as well as much more concise/idiomatic, to use the unary +:

data.map(obj => ({a: +obj.a, b: +obj.b, c: +obj.c}));

I guess I'm in the minority, but I'll leave this here anyway in case this is useful to someone.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
1

Personally I would use lodash mapValues for this.

const parsed = data.map(item => _.mapValues(item, parseFloat))

This simply takes each item, and iterates over the keys, changing the value using parseFloat. Compared to the reduce method, this is much more readable, and less prone to bugs as you aren't reinventing the wheel.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
1

You can accomplish this with some simple for loops.

const data = [
 {a: '12.03', b: '2.45', c: '24.12'},
 {a: '12.03', b: '22.45', c: '44.12'},
 {a: '15.03', b: '12.45', c: '24.12'},
];

//Loop through each array
for (var arr in data){
//Loop through eact data point
        for (var point in data[point]){
    //Convert to float
            data[point][i] = parseFloat(data[point][i])
    }
}
0

You can use javascript parseFloat() to convert a string into a float.

parseFloat('12.03')

returns

12.03
michele
  • 23
  • 5
0

You can map over each of the data items and transform them into your desired format:

const result = data.map(value => ({ 
  a: parseFloat(value.a), 
  b: parseFloat(value.b), 
  c: parseFloat(value.c) 
});
Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
0

You run a function through every element of the array with .map (every object), then if you don't know the keys or the amount of keys, you can loop through each of the object's key with Object.keys(el), and then using parseFloat to do the trick.

data.map((el) => {
  Object.keys(el).forEach((key) => {
      el[key] = parseFloat(el[key])
  })
})
Teh SoTo
  • 209
  • 1
  • 10