javascriptjsonreactjsmaterial-uireact-data-grid

Material UI datagrid with nested data


How do I render nested JSON data on react material UI data grid. In the sandbox attached I want to show the phone numbers of the users from the json on the data grid-Nested JSON Data Grid


Solution

  • To solve the problem, let's see params object passed in valueGetter function. Log that and you will find a row object under it. Instead of using params.getValue(), you should access the row object. It seems that params.getValue() can only be used on one-level JSON object. Here is the code snippet to output phone field.

      {
        field: "phone",
        headerName: "Phone",
        width: 160,
        valueGetter: (params) => {
          console.log({ params });
          let result = [];
          if (params.row.phone) {
            if (params.row.phone.home) {
              result.push("home: " + params.row.phone.home);
            }
            if (params.row.phone.office) {
              result.push("office: " + params.row.phone.office);
            }
          } else {
            result = ["Unknown"];
          }
          return result.join(", ");
        }
      }
    

    Update

    To have more flexibility on checking if every key under a object exists, I have created a helper method:

    const checkKeysUnderObject = (obj, result) => {
      for (let key in obj) {
        if (key) { // push the value to the result array only if key exists
          result.push(key + ": " + obj[key]);
        }
      }
    };
    

    usage of the helper method:

    if (params.row.phone) {
      checkKeysUnderObject(params.row.phone, result);
    }else{
      result = ["Unknown"];
    }
    

    I have also updated the codesandbox here.