Search code examples
reactjsmaterial-uidatagrid

React JS Material UI DataGrid: how to join data between multiple table?


I have a dataGrid with React and Material UI. All data comes from table A which is structured as follows:

{Name: foo, Surname: Fry, Job Position: 3}

Then there is a table B which contains the correspondences of the various works eg:

{id: 3, Job: "comic"}
{id: 4, Job: "actor"}
etc...

how do i show "comic" in the grid instead of "3" as in the example? A thousand thanks


Solution

  • You can process your data using the map() function. If your original data is in an array called people:

    const people = [
      {name: "Alice", surname: "Alman", job:3}, 
      {name: "Bob", surname: "Briscoe", job:3}, 
      {name: "Carol", surname: "Conway", job:1}, 
      {name: "Dan", surname: "Dunne", job:2}, 
    ]
    

    And you have the second table available

    const jobs = [
      {id: 1, job:"Programmer"}, 
      {id: 2, job:"Actor"}, 
      {id: 3, job:"Comic"}, 
      {id: 4, job:"Manager"}, 
    ]
    

    Then before passing the data to the grid you can do the following map to add the job title to each record:

    const data = people.map(person => {
      const job = jobs.find(job => job.id == person.job);
      return {...person, title: job.job}
    });
    

    Which ends up with these values:

    [{ "name": "Alice", "surname": "Alman", "job": 3, "title": "Comic" }, { "name": "Bob", "surname": "Briscoe", "job": 3, "title": "Comic" }, { "name": "Carol", "surname": "Conway", "job": 1, "title": "Programmer" }, { "name": "Dan", "surname": "Dunne", "job": 2, "title": "Actor" }]