Search code examples
ag-gridag-grid-react

AG-Grid Concat fields


I'm trying to concat multiple fields in AG Grid. This is working but when the field is blank the grid shows undefined.

See my code below. I have a grid that has a students First, Middle and Last Name. However, when the Middle name is blank, the 'Student' field, where the values are concatenated it shows the middle name as undefined.

this.state = {
      modules: AllCommunityModules,
      columnDefs: [
        {
          field:"FirstName",
          headerName: "FirstName",
        },

        {
          field: "MiddleName",
          header: "MiddleName",
        },

        {
          field: "LastName",
          header: "LastName",
        },

        {
          field: "Student",
          header: "Student",
          valueGetter: studentValueGetter,
        },

function studentValueGetter(params) {
  return params.data.FirstName + params.data.MiddleName + params.data.LastName;
}
A header Another header A header Another header
John Pete Smith JohnPeteSmith
Sarah Jane SarahunderfinedJane

Solution

  • Just add a condition on the middle name:

    return params.data.FirstName + ' ' +
      (params.data.MiddleName ? params.data.MiddleName + ' ' : '') +
      params.data.LastName;
    

    Or the same thing with more advanced syntax:

    const { FirstName, MiddleName, LastName } = params.data;
    return [FirstName, MiddleName, LastName].filter(n => !!n).join(' ');
    

    Not an ag-grid specific thing though; this is JavaScript generally.