How to list array of object by its duplicate value

Viewed 41

Need help solving the below exmaple

new Vue({
    el:"#app",
    data: {
     items: [
        { 
            type: "a", 
            Descr: "searching"
        },
        { 
            type: "a", 
            Descr: "maps"
        },
        { 
            type: "b", 
            Descr: "maps and social"
        },
         { 
            type: "b", 
            Descr: "searching"
        },
        { 
            type: "c", 
            Descr: "maps"
        },
        { 
            type: "c", 
            Descr: "maps and social"
        },
         { 
            type: "any_value", 
            Descr: "maps and social"
        }
    ]
    },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="(item,i) in items" :key="i">
         <div>{{item.type}}</div>
         <div>{{item.Descr}}</div>
    </div>
</div>

what i am getting

a
searching
a
maps
b
maps and social
b
searching
c
maps
c
maps and social
any_value
maps and social

what i want in output

   a   
 --------   
 * searching
 * maps
 
     b  
 --------   
 * maps and social
 * searching
 
      c  
 --------   
 * maps
 * maps and socials


     any_value  
 --------   
 * maps and social

Note : type and Descr can be any value,but i want them to list under the type like above example

hightly appreciated if it can be done using a single v-if property.

-------------------------------End------------------------------------------- this line is because the error saying It looks like your post is mostly code; please add some more details

1 Answers

You need to group elements, one way would be:

new Vue({
    el:"#app",
    data() {
      return {
        items: [
          {type: "a", Descr: "searching"},
          {type: "a", Descr: "maps"},
          {type: "b", Descr: "maps and social"},
          {type: "b", Descr: "searching"},
          {type: "c", Descr: "maps"},
          {type: "c", Descr: "maps and social"},
          {type: "any_value", Descr: "maps and social"}
        ]
      }
    },
    computed: {
      grouped() {
        return this.items.reduce(
          (result, item) => ({
            ...result,
            [item['type']]: [
              ...(result[item['type']] || []),
              item,
            ],
          }), 
          {},
        )
      }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul v-for="(group, key) in grouped" :key="key">
    {{ key }}
    <li v-for="(item, i) in group" :key="i">
       {{ item.Descr }}
     </li>
  </ul>
</div>

Related