Home » vue » What is the best way extract a key and value from Axios response object?

What is the best way extract a key and value from Axios response object?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a Mongoose schema that records a key:value pair in a mixed type array like this:

Mongoose

const budgetSchema = new Schema({
  earnings: Number,
  expenses: [mongoose.Schema.Types.Mixed]
});
bugdet:{
  earning:1000,
  expenses: [
{shopping: 300},{bills:700}
]
}

In Vue.js I request the data using Axios and it is working fine but when I display the expenses property it displays as {shopping:300}.

Vue js

<template>
  <div class="about">
    <h1>My Budget</h1>
    {{ myExpenses }}
  </div>
</template>

<script>
import axios from "axios"
export default {
  name: "myBudget",
  data() {
    return{
        myExpenses:[]
    }
  },
  methods: {},
  mounted(){
      axios.get("http://localhost:3000/budget",{
          headers:{"Content-Type": "application/json"},
          withCredentials: true
      }).then(res =>{
          this.myExpenses =  res.data.budget[0].expenses[0]
      })
  }
};
</script>

I would like to display the “expenses” data’s key and value separately. Is there any way I can extract the object?

Answers:

It seems like you have axios pretty well handled, and from my interpretation of your question, you’re really trying to access the data that axios returns to you. The following examples don’t use axios, but assume that the static data in the data method is the same as what you’ve retrieved from axios already. One thing I did note about your data however is that you’re only grabbing the first index of expenses. You might want to do something like this.myExpenses = res.data.budget[0].expenses, which would return the entire list of expenses, rather than just the first value.

This is what I believe you’re attempting to do:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </head>
  <body>
    <div id="app">
      <h1>My Budget</h1>
      <div v-for="expense in myExpenses">
        <div>Name:{{ Object.keys(expense)[0] }}</div>
        <div>Total:{{ Object.values(expense)[0] }}</div>
        <hr />
      </div>
    </div>
  </body>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        myExpenses: [{ shopping: 300 }, { bills: 700 }]
      }
    });
  </script>
</html>

However, I would recommend changing the schema to return objects that look like this

{ name: 'shopping', total: 300 }

This pattern more effectively uses the object’s structure to specify the name of its fields and their associated values. It would also allow you to do something more like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  </head>
  <body>
    <div id="app">
      <h1>My Budget</h1>
      <div v-for="expense in myExpenses">
        <div>Name:{{ expense.name }}</div>
        <div>Total:{{ expense.total }}</div>
        <hr />
      </div>
    </div>
  </body>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        myExpenses: [
          { name: 'shopping', total: 300 },
          { name: 'bills', total: 700 }
        ]
      }
    });
  </script>
</html>

###

You could use destructuring:

const {
  data: {
    budget: [firstElement]
  }
} = res;

and work with firstElement variable which will be equal res.data.budget[0];