Accessing the ID within an array object using Vue.js

As a newcomer to Vue.js, I am dealing with data stored in an array object as shown below when using vue-multiselect:

    [
        {
            "id": 1,
            "add_on_type": "Xtra",
            "name": "test",
            "price": 12,
            "created_at": "2020-06-25 10:12:43",
            "updated_at": "2020-06-25 10:12:43"
        },
        {
            "id": 3,
            "add_on_type": "Xtra",
            "name": "Some x",
            "price": 120,
            "created_at": "2020-06-30 05:47:52",
            "updated_at": "2020-06-30 05:47:52"
        }
    ]

However, my function requires me to access the data in key:value format like this:

"xtra": {
  // key: value
  0: 1
  1: 3
}

Unfortunately, instead of getting just the ID values from the array, I'm receiving all the array objects. Here is a snippet of my code where I'm struggling to extract only the ids:

this.$axios
      .get("items/" + this.item)
      .then(res => {
        // The line below shows how I currently access the array object, but I need only the ids.
        data.xtra = this.extra;
        console.log(data);
      })
      .catch(err => {
        throw err;
      });

While some may find this task straightforward, I'm having difficulty figuring it out on my own. Any guidance or assistance would be greatly appreciated. Thank you in advance!

Answer №1

Based on my understanding of your query, this.item contains an object that has been fetched from the array. If this is the case, it can be simplified to:

  .fetch("items/" + this.item.id)

Answer №2

To generate a new array, consider creating it upon receiving the response from axios

.then(response => {
  let newArray = response.data;
  this.newArray = newArray.map(item =>
    item.id);
 })

Answer №3

Start by creating a reactive array called "tools" within the setup function

 const tools = reactive([]);   

Next, in the methods section, make an API call to retrieve user items:

axios.get("/user-items").then(response => {
                            
       var items = [];
       response.data.forEach((item, index) => {
           items.push(item.id);
       })
       Object.assign(this.items, items);
                        
});

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

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

What is the process for implementing text box validation on a button click within a gridview in asp.net utilizing javascript?

How can I implement textbox blank validation on button click within a gridview using JavaScript? My gridview has multiple rows with 2 textboxes and a save button in each row. I need to validate the textboxes when their corresponding save button is clicked. ...

Find the following div that is directly beneath the td element

How can I dynamically hide a div with the class "question" based on the values in $row[12]? <td class="status"> <div class="recstatus">$row[12]</div> <div class="question"> //something </div> </t ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Unexpected error encountered with the release of Angular 2: "Module import of 'ElementRef' resulted in an unexpected value"

After upgrading to Angular 2, I encountered an error related to ElementRef. Initially, I received the error message Angular2 RC5 error:zone.js: Unhandled Promise rejection: No provider for ElementRef which was discussed on this thread. I adjusted my code a ...

Updating an image source using JavaScript without relying on a default image source specified in the HTML code

Struggling to change the image source path using JavaScript? Want to change the page color randomly after each load? I created SVGs in different color types - blue, red, yellow... but can't get it to work. The path seems correct when tested normally i ...

Add a Bootstrap Popover to the Amazon website

Currently, I am developing a straightforward chrome extension and my aim is to incorporate a basic bootstrap popover on a product page from amazon.com using my content.js script. To achieve this, I have implemented the following code within content.js for ...

There seems to be a lack of update in the fragment shader due to mouse movement

Struggling to incorporate the Voronoi shader from the Book of Shaders into three.js, I can't figure out why the mouse position isn't affecting my visible output. Even though I'm logging the mouse position and checking that the uniform value ...

Save the webpage source code to a file using JavaScript and Grunt

I am facing an issue and need assistance with my project. I have developed an app using GruntJs and now I need to download the source code of a webpage using GruntJs. For instance, let's assume I have a webpage at: example.com/index.html. What I wou ...

Using jQuery, adjust the width of child elements within a container by applying dynamic CSS styling

I am attempting to dynamically set the width of several child elements using jQuery. Here is what I am trying to achieve: Obtain the count of the desired containers (since there will be multiple instances of the .steps-container class in the DOM) Iterate ...

When capturing photos using h5 on iOS devices, the browser may experience a flash back issue

I have been searching Baidu and Google for a while now, but I still haven't found a solution. Here is the specific issue: When using h5 to take photos on iOS systems, the browser flashes back. HTML Code <img src="xxx" onclick="sta ...

Unable to retrieve PHP data using AJAX

Index.html → <form> <div class="form-group"> <!-- <input type="text" id="name" class="form-control" placeholder="Enter Name"> --> </div> <div ...

Node.js exec command encountering an uninformative error message and not executing properly

Here is the snippet of code that needs to be executed cp.exec("cc -Wall /tmp/test.c -o /tmp/test", function(e, stdout, stderr) { if (e) { var errorstr = "There was an error during compilation: "+ e.message.toString() ...

How can I best access the object being exposed on the webpage using <script type="text/json" id="myJSON">?

In our current project, we are successfully using AMD modules to organize and structure our code. One idea I have is to create an AMD module that accesses a script tag using a jQuery ID selector and then parses the content into JSON format. Here's an ...

Is it possible to save user inputs in a .json file for future use, and retrieve and reuse them in subsequent sessions or processes?

I am currently developing an account generator using puppeteer and I have a specific requirement for user inputs. The script prompts the user to input necessary variables, but I am interested in exploring the possibility of storing these inputs in a JSON ...

What is the best way to allocate 40% of a view's height in Ionic?

How can I set the height to 40% of the view in Ionic? I want my code to run on all screen resolutions, so I am using a percentage for the view height. However, when I set it to 40%, it takes up less space than expected. On the other hand, setting it to 200 ...

What is the best way to check for data changes in my Vue JS application using Jest for unit testing?

Currently, I am in the process of unit testing my code using Jest within my frontend Vue JS project. One particular test that I aim to write involves: it('should display the advanced filters if a user_id is present', () => { }) This test p ...

Is there a method to invoke a mixin from the root instance without relying on $root?

Hello there, I need some guidance: I want to invoke the method below without using $root beforehand. Is that achievable? I am working with Vue Single File Components. Here is my code: //app.js const mixin = { methods: { makeToast(title = "", content ...

Executing Connected Json Requests Using JavaScript

I'm currently working on a project that involves making multiple JSON calls inside a loop. After exiting the loop, I need to handle the results from all these calls. However, my issue lies in understanding how to ensure that the order of operations is ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...