Skip to content Skip to sidebar Skip to footer

How To Group Array Key Value

I am getting API response as below [{id: 1, fileName:'abc.png',docid:'123',controlNumb:'11'}, {id:2,fileName:'mno.png',docid:'121',controlNumb:'12'}, {id:1,fileName:'def.png',docid

Solution 1:

U can loop over the data, and group the values based on the same id, then expand the properties of fileName and docid to arrays, for example:

const data = [{ id: 1, fileName: "abc.png", docid: "123", controlNumb: "11" },
{ id: 2, fileName: "mno.png", docid: "121", controlNumb: "12" },
{ id: 1, fileName: "def.png", docid: "120", controlNumb: "11" },
{ id: 3, fileName: "xyz.png", docid: "125", controlNumb: "13" },
{ id: 2, fileName: "rst.png", docid: "126", controlNumb: "12" }];

const parsedData = [];

for (const item of data) {
  const index = parsedData.findIndex(storedItem => storedItem.id === item.id);
  if (index === -1) {
    const newItem = { ...item, fileName: [item.fileName], docid: [item.docid] }
    parsedData.push(newItem);
    }
  else {
    parsedData[index].fileName.push(item.fileName);
    parsedData[index].docid.push(item.docid);
  }
}

console.log(parsedData);

Solution 2:

For this kind of operation I suggest using Lodash. It's a very cool library with tons of useful methods to help you on your project.

https://lodash.com/docs/

Lodash has a groupBy method, easy to use, and I believe it does what you are looking for. So in your case, you would have something like this:

const newDirectory = _.groupBy(this.state.data, "id");

You basically pass the array you want to group, along with the key name you want to group by.

Hope this was helpful.

Post a Comment for "How To Group Array Key Value"