ST80
ST80

Reputation: 3903

Vue how to merge nested arrays into one single array

I have an array with multiple objects, which also contain an array.

[
 {
   title : "some title",
   items: [
       {
        "title" : "some title",
        "value" : "some value"
       }
     ]
 },
 {
   title : "some title",
   items: [
       {
        "title" : "some title",
        "value" : "some value"
       }
     ]
 },
 {
   title : "some title",
   items: [
       {
        "title" : "some title",
        "value" : "some value"
       }
     ]
 }
],
[
 {
   title : "another title",
   items: [
       {
        "title" : "some title",
        "value" : "some value"
       }
     ]
 },
 {
   title : "another title",
   items: [
       {
        "title" : "some title",
        "value" : "some value"
       }
     ]
 },
 {
   title : "another title",
   items: [
       {
        "title" : "some title",
        "value" : "some value"
       }
     ]
 }
]

In my vue-component I did this:

    <ul>
        <li v-for="group in data" :key="group.title">
            <h3>{{group.title}}</h3>
            <div> 
               <div v-for="item in group.items" :key="item.id"/>
                   {{ item.value }}
               </div>
        </li>
   </ul>

this works fine so far, but now I don't want to split them up and just want to output all without the {{group.title}} - kind of merge them together. How can I solve this?

Upvotes: 0

Views: 445

Answers (1)

torbilote
torbilote

Reputation: 141

I am not sure if I understand your question correctly so let me try. If you do want to display all items' values of all objects in the array, there are two ways to achieve that.

  1. In case you dont want to add any extra data properties etc. and you want to handle it directly in html, you can just simply use template tag (which is not rendering on the page) to use v-for on it. For your case it should look like below (keeping same html tags):
    <ul>
       <template v-for="group in data" :key="group.title">
          <li v-for="item in group.items" :key="item.id">
            <div>
              {{item.value}}
            </div>
          </li>
       </template>
    </ul>
  1. In case you want to have simpler html code you can create computed property in which you will use in html. Example: (I believe there are more efficient ways to do that but this is first solution in my mind).
    <ul>
          <li v-for="item in items" :key=item.id>
            <div>
              {{item.value}}
            </div>
          </li>
    </ul>
   ...
   ...
   computed: {
     items: {
       const newArr = []
        for(let i = 0; i<data.length; i++) {
          for(let j = 0; j<data[i].items.length; j++) {
            newArr.push({
              value: data[i].items[j].value,
              id: `${i}-${j}`,
           })
          } 
        } 
     return newArr
   }
  }

Upvotes: 2

Related Questions