-1

I am attempting to convert an api from PHP to react.js. my data looks like this:

s c d
A 1 4/1
B 4 4/1
A 2 4/2
B 5 4/2
A 3 4/3
B 6 4/3

I pass json back to the app and it's built like this in PHP.

     $graph_arr['bar']['series'][$s] += (int) $c;
     $graph_arr['line']['series'][$s][] = (int) $c;

the resulting json looks like this

{line: 
   {labels: ['4/1','4/2','4/3'],  //already have this figured out 
    series: [{ name: 'A', data: [1,2,3]},
             { name: 'B', data: [4,5,6]}
  ]}
}

How would I do this in react, new to react.js so I am not too familiar everything works or is constructed yet.

  const graph_data = [['a',1,'4/1'],['a',2,'4/1'],['a',3,'4/1'], 
       ['a',4,'4/4'],['b',5,'4/1'],['b',6,'4/1'],['b',7,'4/1'],['b',8,'4/4']]

     const series = Object.entries(graph_data).map((row,i) => { })

edit: found this How to group an array of objects by key. which is close

1 Answers1

-1

You can treat it just like you do an array in PHP.

jsonData["line"]["series"][0].name

You can also extract (deconstruct) the data out

const jsonData = {
  line: {
    labels: ["4/1", "4/2", "4/3"], //already have this figured out
    series: [
      { name: "A", data: [1, 2, 3] },
      { name: "B", data: [4, 5, 6] }
    ]
  }
};

  const { line } = jsonData;
  const { labels, series } = line;

 {labels}   
 {labels[0]}
 {series.map((data) => data.name)}

I put them in an example with a couple of different ways for you: https://codesandbox.io/s/determined-keller-3ott6?file=/src/App.js

Sir Codes Alot
  • 1,149
  • 8
  • 11
  • Thanks! The jsonData is what I'm looking to create from const data = {['a',1,'4/1'],['a',2,'4/1'],['a',3,'4/1'],['a',4,'4/4'],['b',5,'4/1'],['b',6,'4/1'],['b',7,'4/1'],['b',8,'4/4']}. sorry for the confusion – itsjustcarlos Apr 09 '21 at 17:52