Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert values from certain keys of an array to numbers?

I have the following array of objects

const mi_array = [{
  agrupacion: "Total país",
  col2015: '81.8',
  col2016: '86.4',
  col2017: '67.3',
  col2018: '70.8',
  col2019: '67.6'
},{
  agrupacion: "otra cosa",
  col2015: '90.8',
  col2016: '67.4',
  col2017: '39.3',
  col2018: '50.8',
  col2019: '95.6'
}];

I need to transform this into something like this:

const new_array = [{
  name: "Total país",
  data: [81.8, 86.4, 67.3, 70.8, 67.6]
}, {
  name: "otra cosa",
  data: [90.8, 67.4, 39.3, 50.8, 95.6]
}];

I tried this but since values on keys col2015 thru 2019 are all strings, it doesn’t work as intended

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const result = mi_array.map(e => ({
  name: e.agrupacion,
  data: Object.values(e).filter(e => typeof e == 'number')
}))

console.log(result)

output:

[{
  data: [],
  name: "Total país"
}, {
  data: [],
  name: "otra cosa"
}]

I know it will work if I can transform those values into numbers somehow so i tried to achieve that with this:

for(let key of Object.keys(mi_array))  mi_array[key] = +mi_array[key]

console.log(mi_array);

however my output is:

[NaN, NaN]

another attempt:

var result = Object.keys(mi_array).map(function(key) {
  return [Number(key), mi_array[key]];
}); 

console.log(result); 

another failed output:

[[0, {
  agrupacion: "Total país",
  col2015: "81.8",
  col2016: "86.4",
  col2017: "67.3",
  col2018: "70.8",
  col2019: "67.6"
}], [1, {
  agrupacion: "otra cosa",
  col2015: "90.8",
  col2016: "67.4",
  col2017: "39.3",
  col2018: "50.8",
  col2019: "95.6"
}]]

Is there an efficient way of doing this?

>Solution :

You could destructure name and take from the rest only the values as data, after mapping with Number.

This approach takes the original order of the object.

const
    mi_array = [{ agrupacion: "Total país", col2015: '81.8', col2016: '86.4', col2017: '67.3', col2018: '70.8', col2019: '67.6' }, { agrupacion: "otra cosa", col2015: '90.8', col2016: '67.4', col2017: '39.3', col2018: '50.8', col2019: '95.6' }],
    result = mi_array.map(({ agrupacion: name, ...o }) => ({
        name,
        data: Object.values(o).map(Number)
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading