Extract the property value and save it as an array in Vue

Looking to extract all values of a specific property and save them as an array. I attempted the following method:

data() {
    return {
       roomList: null
    }
},
methods: {
     getRooms() {
        var that = this
        axios.get('http://localhost:3000/roomList')
              .then(function(response) {
                that.roomList = response.data
            })
        let roomLists = that.roomList.map(i => i.name) //extracting property values
        return roomLists;
    },

},
mounted: function () {
        this.getRooms()
},

I suspect I may have misplaced the map function. I tried placing it inside the data section but encountered issues. I'm struggling to determine the appropriate location for this function. Any guidance or assistance would be greatly appreciated. Thank you.

Answer №1

To effectively manage the data, I recommend storing the entire roomsList data in your component's data property and creating a computed property to extract only the names that will be kept synchronized with the original data.

Make sure to initialize the roomsList as an empty array.

export default {
  data: () => ({ roomsList: [] }),
  computed: {
    roomNames: ({ roomsList }) => roomsList.map(({ name }) => name)
  },
  methods: {
    async getRooms () {
      const { data } = await axios.get('http://localhost:3000/roomList');
      this.roomsList = data;
    }
  },
  mounted () {
    this.getRooms()
  },
};

Your template would then have a structure like the following example:

<ul>
  <li v-for="roomName in roomNames">{{ roomName }}</li>
</ul>

Answer №2

If I have grasped your message correctly, please refer to the code snippet below:

const app = new Vue({
  el: "#app",
  data() {
    return {
       itemList: null
    }
  },
  computed: {
    itemLists() {
      return this.itemList?.map(item => item.name)
    }
  },
  methods: {
     getItems() {
       axios.get('https://jsonplaceholder.typicode.com/posts')
        .then((response) => {
          this.itemList = response.data
      })
    },
  },
  mounted() {
    this.getItems()
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha256-7ixQw+mUpRYg3Dqa3ClWUKzJWKIFF1jTdyZ+NVcyW54=" crossorigin="anonymous"></script>
<div id="app">
  {{itemLists}}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embed schema information into HTML tags using JavaScript

Is there a way to insert text, specifically schema data, into an HTML div tag using JavaScript? While I know how to modify existing values within a tag like class, href, and title, I am struggling to find a method to add something entirely new. Essentiall ...

Transforming into a serialized division

I am working on creating a custom WISYWIG editor that generates a div with specific inner elements. The goal is to design the div (along with its inner structure), serialize it, store it in a database as a string or JSON format, and later insert it into th ...

Issues with v-on:change not triggering method in nuxt.js

Despite my efforts, I can't seem to get this seemingly simple task to work. I came across a question on Stack Overflow that seemed to address the issue - how to fire an event when v-model changes Here is the component that I am working with: <tem ...

The JavaScript Autocomplete feature fails to clear suggestions when there is no user input detected

After watching a tutorial on using Javascript with Autocomplete and a JSON file, I implemented the code successfully. However, I encountered an issue: When I clear the input field, all results from the file are displayed. I've tried adding code to cl ...

Toggle visibility of a div with bootstrap checkbox - enforce input requirements only if checkbox is marked

Lately, I've been facing a strange issue with using a checkbox that collapses a hidden div by utilizing bootstrap. When I include the attribute data-toggle="collapse" in the checkbox input section, the div collapses but it mandates every single one o ...

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

Suggestions to reduce our website loading time

Query: How can one effectively reduce the file size of a webpage to improve loading speed? What specific optimization practices and coding techniques (in JavaScript and PHP) can be implemented to decrease page weight? Motivation: After reading an article ...

Sinon - using callbacks in stubbed functions leading to test method exceeding time limit

One of my express route methods is structured as follows: exports.register_post = function(req, res) { var account = new Account(); account.firstName = req.param('firstName'); //etc... account.save(function(err, result) { ...

I am looking to include both the type and maxLength attributes in a MUI TextField

<TextField value={ele.mobile} helperText={ferrors[id]?.mobile} name="mobile" classes={{ root: classes.textField }} InputProps={{ clas ...

Layer one image on top of another using z-index

I'm having trouble layering one image on top of another in my code. Here is my code: body { background: #000000 50% 50%; height: 100% width:100%; overflow-x: hidden; overflow-y: hidden; } .neer { z-index: 100; position: absolute; } ...

The json_encode() function yields an empty result

I am facing an issue with a PHP script that is supposed to parse an array using the json_encode() method, but it returns a blank output. Here is the PHP code snippet: $companies = $db->getCustomerNames(); print_r($companies) if (!empty($companies)){ $ ...

"Eliminate the headers of columns within the collapsible rows on the ui-grid interface

I am working with an expandable table and trying to figure out how to hide the column headers for only the expandable rows within the table. I experimented with including showHeader : false in the subGridOptions, but without success as the headers are stil ...

The functionality of selecting all items in v-select does not result in saving all of them

I'm currently working on integrating a select all button into the v-select component of Vuetify. The issue I am facing is that even though I can use the button to select all options, when I attempt to save, not all items are saved. However, if I manua ...

Embedding a YouTube video in an iframe triggers numerous cautionary notifications in the Chrome browser

I have a website with numerous YouTube links embedded in iframes. However, the page loads extremely slowly and some of the YouTube images do not load at all. The website is built using PHP. Even with just 7 YouTube links, the Chrome browser generates over ...

Is there a way to convert a button into clickable text that performs the same function as the original button?

Seeking a solution to transform a button into clickable text with the same functionality. Explored resources like Google, StackOverFlow, and Youtube for answers. This is the current code snippet representing the button: <button onclick="mainApp.l ...

Encountering a problem sending an array of objects to a controller via jQuery AJAX

I attempted to send an array of objects to a controller using jQuery Ajax, but I am getting a null result in ASP.NET 5.0. The data array that I'm sending is named regions. The constructor for the data is defined in the BoundingBoxModel class. Here i ...

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

How do I return a <div> element to its initial state after JavaScript has made changes to it?

So, I have this situation where a DIV contains a form. After users submit the form successfully, I want to replace the form with a simple message saying "everything is good now". This is how I currently do it: $("#some_div").html("Yeah all good mate!"); ...

I am trying to showcase a collection of images on my homepage, but unfortunately, it is not functioning as expected

Does anyone know how to display images using Angular? I am currently utilizing the pic controller in an AngularJS file. Any assistance would be greatly appreciated. HTML CODE <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

AngularJS: Component fails to load controller

I am managing a directory structure that looks like this --- js/app.js ------- components ----------- header -------------- headerComponent.html -------------- headerComponent.js -------------- headerController.js Within index.html, I have the following ...