Home > Back-end >  How to groupBy and iterate on object/array with a .reduce in Vue?
How to groupBy and iterate on object/array with a .reduce in Vue?

Time:10-27

Suppose I have an array and never know what different ID's are contained. How can I group and display them dynamically? Because I will never know how many different ID's are located, I will never know how many different arrays will be created too.

Theoretically, I think we need to group all objects by these ID's and push them into new arrays. These arrays could be named as 'array-0', 'array-1', ... After that, we need to count how many arrays have been created and loop through the items by item in array-["n in nArrays"]. I'm sure this won't work this way because I think we can't dynamically create loops like this, but it's for a better explanation of my idea.

array: [
  { id: 11, item: "item" },
  { id: 49, item: "item" },
  { id: 11, item: "item" },
  { id: 20, item: "item" },
  { id: 49, item: "item" },
  { id: 83, item: "item" },
]
<div v-for="item in array-0">
  {{ item }} // all items with id 11 e.g.
</div>

<div v-for="item in array-1">
  {{ item }} // all items with id 20 e.g.
</div>

But it should be dynamic

<div v-for="item in array-[n in nArrays]">
  {{ item }}
</div>

CodePudding user response:

You could use enter image description here

  • Related