[Vuejs]-Create grouped table with array of objects in Javascript

0πŸ‘

I am not familiar with vue but you have to change buildObjects function to retrieve list like the below :

items = [
{Type:"0001",Build:"light",Weight:1,Volume:1,rowspan:3},
{Type:"0001",Build:"light",Weight:1,Volume:1},
{Type:"0001",Build:"heavy",Weight:4,Volume:1},
{Type:"0002",Build:"light",Weight:2,Volume:3,rowspan:2},
{Type:"0002",Build:"light",Weight:2,Volume:3},
{Type:"0003",Build:"light",Weight:1,Volume:1,rowspan:3},
{Type:"0003",Build:"light",Weight:1,Volume:1},
{Type:"0003",Build:"heavy",Weight:5,Volume:3},
{Type:"0004",Build:"light",Weight:1,Volume:1,rowspan:1}
];

and change your html code to equivalent the below angular code

<tr *ngFor="let item of items">
    <td  *ngIf="item.rowspan" [attr.rowspan]="item.rowspan" >{{item.Type}}</td>
    <td>{{item.Build}}</td>
    <td>{{item.Weight}}</td>
    <td>{{item.Volume}}</td>                            
</tr>

PS: List should be sorted

0πŸ‘

It’s hard to understand if you have access to the Vue script. As you are using Vue at the front end, you should be abble to change your data structure by computed property, then iterate over it.

One example of implementation for what you try to achieve:

refactoredBuildObjects() {
    return Array.from(
        this.buildObjects.reduce((t, v) => {
            if (t.has(v.Type)) {
                const item = t.get(v.Type)

                if (item.Entries.has(v.Build)) {
                    const entry = item.Entries.get(v.Build)
                    entry.Weight +=  v.Weight
                    entry.Volume += v.Volume
                    entry.Count++

                    item.Entries.set(v.Build, entry)
                }
                else {
                    item.Entries.set(v.Build, { Build: v.Build, Weight: v.Weight, Volume: v.Volume, Count: 1 })
                }

                t.set(v.Type, item)
            }
            else {
                t.set(v.Type, {Type: v.Type, Entries: new Map([[v.Build, { Build: v.Build, Weight: v.Weight, Volume: v.Volume, Count: 1 }]]) })
            }

            return t;
        }, new Map()).values()
    ).map(item => {
        item.Entries = Array.from(item.Entries.values())
        return item
    })
}

I made a Fiddle for a full implementation.

Leave a comment