Home > Blockchain >  ReactJS Convert json to [name: value:] pair
ReactJS Convert json to [name: value:] pair

Time:11-30

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.

CodePudding user response:

You can just use map to return a new array with values from old array

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

const newData = data.map(item => {
  return {
    name: item.crime,
    value:  item.count //   to convert string to number
  }
});

console.log(newData)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
}))
  • Related