Home > Back-end >  Show title for each group that is grouped by value from array of object
Show title for each group that is grouped by value from array of object

Time:06-29

I am receiving data as an array of objects in JS. Each object has a value month and I want to show data with groups according to month. Example:

data: [
{id: 0001,month:2,desc:'objectone'},
{id: 0001,month:4,desc:'objecttwo'},
{id: 0001,month:4,desc:'objectthree'},
{id: 0001,month:4,desc:'objectfour'},
{id: 0001,month:5,desc:'objectfive'},
{id: 0001,month:5,desc:'objectsix'}
]

Now I want to show it like this:

<h1>Month {month}</h1>
<p>{desc}</p>

Month 2 objectone

Month 4 objecttwoo objectthree objectfour

Month 5 objectfive objectsix

I've used reduce to group it by the value but still having issue in mapping it to show as described above. After reduce I get one object that contains array of objects:

data: {
1:(1) [{...}],
2:(3) [{...}],
3:(2) [{...}]
}

Thanks

CodePudding user response:

After you've grouped the data you can loop through it using Object.entries and then inside the loop create the heading and the para for every month.

const data = [
  { id: "0001", month: 2, desc: "objectone" },
  { id: "0001", month: 4, desc: "objecttwo" },
  { id: "0001", month: 4, desc: "objectthree" },
  { id: "0001", month: 4, desc: "objectfour" },
  { id: "0001", month: 5, desc: "objectfive" },
  { id: "0001", month: 5, desc: "objectsix" },
];

const groups = data.reduce((r, d) => ((r[d.month] ??= []).push(d.desc), r), {});

Object.entries(groups).forEach(([mon, desc]) => {
  const h2 = document.createElement("h2");
  h2.textContent = `Month ${mon}`;
  const p = document.createElement("p");
  p.textContent = desc.join(" ");
  document.body.appendChild(h2);
  document.body.appendChild(p);
});

CodePudding user response:

If you reduce your data into an object of the form

{ monthnum: [desc1, desc2, ...], ... }

you can then iterate the entries of the object, putting the key in an h1 and each of the desc values in a p:

input = { 
  data: [
    {id: 0001,month:2,desc:'objectone'},
    {id: 0001,month:4,desc:'objecttwo'},
    {id: 0001,month:4,desc:'objectthree'},
    {id: 0001,month:4,desc:'objectfour'},
    {id: 0001,month:5,desc:'objectfive'},
    {id: 0001,month:5,desc:'objectsix'}
  ]
}

months = input.data.reduce((acc, { month, desc }) => {
  acc[month] = (acc[month] || []).concat(desc)
  return acc
}, {})

Object.entries(months)
  .forEach(([m, v]) => {
    const h = document.createElement("h1")
    h.textContent = `Month ${m}`
    document.body.appendChild(h)
    v.forEach(d => {
      const p = document.createElement("p")
      p.textContent = d
      document.body.appendChild(p)
    })
  })
h1 {
  font-size: 20px;
}

  • Related