Home > Back-end >  How to simplify multiple condition check on data restructuring function in javascript?
How to simplify multiple condition check on data restructuring function in javascript?

Time:07-29

Hi I am having an array like this

let data = [
    {
      managerName: "Surendher",
      advisorName: "Kamal",
      clientName: "Shaadi",
      clients: ["client1", "client2"],
    },
    {
      managerName: "Suresh",
      advisorName: "Kamal",
      clientName: "Nikolai",
      clients: ["client3", "client4"],
    },
    {
      managerName: "LN",
      advisorName: "Ravi",
      clients: ["client5"],
    },
  ];

I converted the above array into like this


[
  {
    "advisorName": "Kamal",
    "managerName": "Surendher",
    "clientName": "Shaadi",
    "subRows": [
      {
        "clientName": "",
        "managerName": "",
        "advisorName": "",
        "client": "client1"
      },
      {
        "clientName": "",
        "managerName": "",
        "advisorName": "",
        "client": "client2"
      }
    ]
  },
  {
    "advisorName": "Kamal",
    "managerName": "Suresh",
    "clientName": "Nikolai",
    "subRows": [
      {
        "clientName": "",
        "managerName": "",
        "advisorName": "",
        "client": "client3"
      },
      {
        "clientName": "",
        "managerName": "",
        "advisorName": "",
        "client": "client4"
      }
    ]
  },
  {
    "advisorName": "Ravi",
    "managerName": "LN",
    "client": "client5"
  }
]

By using the below code, I have converted the data into the desired output.


let res = data.map((value) => {
    return value.clients.length > 1
      ? value.managerName
        ? {
            advisorName: value.advisorName,
            managerName: value.managerName,
            clientName: value.clientName,
            subRows: value.clients.map((_, i) => ({
              clientName: "",
              managerName: "",
              advisorName: "",
              client: value.clients[i],
            })),
          }
        : value.advisorName
        ? {
            advisorName: value.advisorName,
            clientName: value.clientName,
            subRows: value.clients.map((_, i) => ({
              clientName: "",
              advisorName: "",
              client: value.clients[i],
            })),
          }
        : {
            clientName: value.clientName,
            subRows: value.clients.map((_, i) => ({
              clientName: "",
              client: value.clients[i],
            })),
          }
      : value.managerName
      ? {
          advisorName: value.advisorName,
          managerName: value.managerName,
          clientName: value.clientName,
          client: value.clients[0],
        }
      : value.advisorName
      ? {
          advisorName: value.advisorName,
          clientName: value.clientName,
          client: value.clients[0],
        }
      : {
          clientName: value.clientName,
          client: value.clients[0],
        };
  });

  console.log(JSON.stringify(res))

But in the above function, you can see most of the code is repeated. Is there any way I could make this above function a simple one with less code?

Checking condition on managerName, advisorName, and clientName. If that present that key and value will be added or else not. And same if clients array length is more than 1 will create a subRows and do some kind of similar process.

And why I am doing this kind of structure because. I am in creating a multi-level expandable table row using @tanstack/react-table. For that, It requires structure like this.

Here u can get the working demo example of this https://codesandbox.io/s/tanstack-table-expansion-sub-level-goe-191pip?file=/src/App.js

Please let me know your suggestions

CodePudding user response:

It seems you want to reproduce the keys of the parent object in the new child object (but with empty string as value), so it would make sense to iterate the keys of this parent object dynamically, instead of checking them in a hard-coded manner:

let data = [{managerName: "Surendher",advisorName: "Kamal",clientName: "Shaadi",clients: ["client1", "client2"],},{managerName: "Suresh",advisorName: "Kamal",clientName: "Nikolai",clients: ["client3", "client4"],},{managerName: "LN", advisorName: "Ravi",clients: ["client5"],},];

const result = data.map(({clients, ...obj}) =>
    clients.length < 2
      ? {...obj, client: clients[0] }
      : {...obj,
            subRows: clients.map(client =>
                Object.fromEntries(
                    Object.keys(obj).map(key => [key, ""])
                                    .concat([["client",client]])
                )
            )
        }
);

console.log(result);

CodePudding user response:

Just another simplification way:

const data = [{managerName: "Surendher",advisorName: "Kamal",clientName: "Shaadi",clients: ["client1", "client2"]},{managerName: "Suresh",advisorName: "Kamal",clientName: "Nikolai",clients: ["client3", "client4"]},{managerName: "LN",advisorName: "Ravi",clients: ["client5"]}];

const emptyClient = {
    clientName: "",
    managerName: "",
    advisorName: "",
};

const makeClients = (clients) => 
    clients.map((client) => ({ ...emptyClient, client }));

const transformed = data.map(({ clients, ...rest }) => {
    const subRows = (clients.length === 1)
        ? { client: clients.at(0) }
        : { subRows: makeClients(clients) };
        
    return { ...rest, ...subRows };
});

console.log(transformed);
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related