Edson
Edson

Reputation: 178

How to Iterate Data in vue.js

I am trying to iterate this data on vue inside the method function

{
  "data": [
    {
      "id": 1,
      "name": "Jack Daniels",
      "mobile": "21223",
      "start": "2021-02-25T09:16:21.000000Z",
      "end": "2021-02-25T09:16:21.000000Z"
    }
  ]
}

here is my code

async getEvents() {
    try {
        const response = await axios.get('/api/customers')

        Object.entries(response).forEach(([key, value]) => {
            console.log(`${key}:${value}`)
        })

    } catch (err) {
        console.log(err)
    }
}

and here is the output on

data:[object Object],[object Object]

any idea what went wrong and if there is better approach for iterating the data in vue.js

Upvotes: 0

Views: 931

Answers (2)

anand shukla
anand shukla

Reputation: 706

Code is fine. Here key is data and value is array of object. so to access value, here is a sample code

let response = {
 "data":[{
 "id":1,
 "name":"Jack Daniels",
 "mobile":"21223",
 "start":"2021-02-25T09:16:21.000000Z",
 "end":"2021-02-25T09:16:21.000000Z"
 }]
};
Object.entries(response).forEach(([key,value])=>{
          console.log(`${key}:${value[0].id}`)
})

Here value is an array so iterate value to get properties. It is just a sample to show logic.

Upvotes: 1

Asimple
Asimple

Reputation: 650

First of all it's not Vue question(axios/js tags).
You don't need Object.entries here (if you need to iterate data array).
Just use map for array and that's all.

const iteratedData = response.data.map((item, index) => {
    console.log(`Index ${index}`);
    console.log(item);
    // Do what you need with data, your iteration
    return item;
});

Upvotes: 1

Related Questions