Home > Enterprise >  Loop Object with Objects in Vue2 template
Loop Object with Objects in Vue2 template

Time:12-13

Hi I use VueJs with TypeScript and I want to loop response result with type Section that have Array of Articles the response looks like:`

{
  {
    id: 1,
    name: "Test",
    articles: [
      {
        id: 1,
        name: "Test",
        price: 1.0,
        quantity: 1
      }
    ]
  },
  {
    id: 1,
    name: "Test",
    articles: [
      {
        id: 1,
        name: "Test",
        price: 1.0,
        quantity: 1
      }
    ]
  }
}

I tried with v-for but does not recognize id prop and the type is not section but

const section: string | number | boolean | Date | Article[] | undefined

CodePudding user response:

First, your object is not JSON valid as @neha mentioned also. It should be like this:

    {
  "obj1":{
    id: 1,
    name: "Test",
    articles: [
      {
        id: 1,
        name: "Test",
        price: 1.0,
        quantity: 1
      }
    ]
  },
   "obj2":{
    id: 1,
    name: "Test",
    articles: [
      {
        id: 1,
        name: "Test",
        price: 1.0,
        quantity: 1
      }
    ]
  }
}

Then you will be able to "loop" like this:

<div id="app">
  <ul>
    <li v-for="(item, key, index) in objectItems">
      {{ item.id }} - {{ key }} - {{ index }}
    </li>
  </ul>
</div>

The example is from DigitalOcean: https://www.digitalocean.com/community/tutorials/vuejs-iterating-v-for

But I strongly suggest you redo the object from the backend so that the main object will be in an array.

  • Related