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

ReactJS Convert json to [name: value:] pair

I have this json object.

[
    {
        "crime": "LARCENY-NON_VEHICLE",
        "count": "23217"
    },
    {
        "crime": "AUTO_THEFT",
        "count": "13675"
    },
    {
        "crime": "LARCENY-FROM_VEHICLE",
        "count": "28627"
    },
    {
        "crime": "BURGLARY-RESIDENCE",
        "count": "16312"
    }
]

I need to display this data in a pie chart so I need to convert it to this format.

[
    {name: "LARCENY-NON_VEHICLE", value: 23217},
    {name: "AUTO_THEFT", value: 13675},
    {name: "LARCENY-FROM_VEHICLE", value: 28627},
    {name: "BURGLARY-RESIDENCE", value: 16312}
    
]

This is how Im retrieving the data using axios.

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

>Solution :

You can simply format an array by calling map function

const arr = [
  {
    crime: "LARCENY-NON_VEHICLE",
    count: "23217",
  },
  {
    crime: "AUTO_THEFT",
    count: "13675",
  },
  {
    crime: "LARCENY-FROM_VEHICLE",
    count: "28627",
  },
  {
    crime: "BURGLARY-RESIDENCE",
    count: "16312",
  },
];

arr.map((e) => ({
  name: e.crime,
  count: Number.parseInt(e.count)
}))
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