Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format JSON data into nested list using Lodash

I am new to lodash, and I have difficulty in formatting data that will display on an expanded table. I have a response of data from the server that looks like this:

[{Day: 1, ItemName: "Item1", Total: 1, Details: "Brand X", Quantity: 5, Part: "Part A"}]

And I wanted it to look like this:

[{
Day: 1,
ItemName: "Item1",
Total: 1,
ItemDetails: [{
     Details: "Brand X",
     Quantity: 5,
     ItemParts: [{
          Part: "Part A"
          }]
     }]
}]

I've used .chain and .GroupBy function and it displays on a table that shows the Day, ItemName and Total rows. Used .map function so when the user clicks the table row it expands and shows the ItemDetails. But unfortunately i dont know how to display the last row or the third nested json data(which is ItemParts) that expands also when the user clicks the ItemDetails.

P.S. You can use any lodash function but please format the data to look like in the description above

P.S.S I only want to format JSON data response, I dont want to modify anything from my table

like image 444
Ivan Gray Avatar asked Jun 08 '26 17:06

Ivan Gray


1 Answers

Something like this without lodash,

const arr = [{
  Day: 1,
  ItemName: "Item1",
  Total: 1,
  Details: "Brand X",
  Quantity: 5,
  Part: "Part A"
}]

const result = arr.map(x => ({
  Day: x.Day,
  ItemName: x.ItemName,
  Total: x.Total,
  ItemDetails: [{
    Details: x.Details,
    Quantity: x.Quantity,
    ItemParts: [{
      Part: x.Part
    }]
  }],
}))

console.log(result)
like image 195
Eugen Sunic Avatar answered Jun 11 '26 07:06

Eugen Sunic