What is the process of converting an object to an Array in ES6?

How can I transform an array of objects called 'urls' into an array where each object is mapped accordingly, considering the properties 'name' and 'url' within each object?

let urls = [{
        "name": "regions",
        "url": context + "ip/region/getAllRegions.do?query="
    },
    {
        "name": "sub regions",
        "url": "context + 'ip/region/getAllSubRegions.do"
    },
];
this.axiosData = urls.map(t => {
    axios.get(t.url)
        .then(res => {

            if (res.data.responseCode == 1) {
                return res.data.payload;
            } else {

                toastr.error("error retrieving " + t.name, "Failure");
            }
        })
        .catch(err => {
            console.log(err);
        });
});

In order to convert 'axiosData' from a single array to an array of arrays containing objects, whereby res.data.payload contains an array of objects, define axiosData in the data section property of Vue instance.

The resulting axiosData structure would resemble something like this:

[[{
"id": 8,
"name_en": "Rangpur",
}, {
"id": 9,
"name_en": "Sylhet",
}, {
"id": 10,
"name_en": "Mymensingh",
}],


[{
"another_id": 8,

}, {
"another_id": 9,

}, {
"another_id": 10,

}]]

Answer №1

To efficiently handle multiple requests, it is recommended to utilize the Promise.all function.

let urls = [{
        "name": "regions",
        "url": context + "ip/region/getAllRegions.do?query="
    },
    {
        "name": "sub regions",
        "url": "context + 'ip/region/getAllSubRegions.do"
    },
];
this.axiosDataPromises = urls.map(t => {
    return axios.get(t.url)
        .then(res => {

            if (res.data.responseCode == 1) {
                return res.data.payload;
            } else {

                toastr.error("error retrieving " + t.name, "Failure");
            }
        })
        .catch(err => {
            console.log(err);
        });
});

Promise.all(this.axiosDataPromises).then(resultArr => {
  this.axiosData = resultArr;
})

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

Extending State Interface in ReactJs and Typescript: A Step-by-Step Guide

I have the following: interface EditViewState<T> { entity?: T; } abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> { constructor(props: P, ctx: any) { super(props, ctx); this. ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...

Having trouble loading images in JavaScript due to an issue with JSON: undefined.jpg not found

I'm struggling to concatenate my image names in this JavaScript code as a newbie, especially since it's pulling from JSON. Any assistance would be greatly appreciated! Below is the JS code snippet I'm working with: function log(msg){ ...

initiate colorbox resizing when parsley validation occurs

Currently, I am using parsley.js validation and colorbox to send a form via ajax. One issue I am encountering is determining how to dynamically resize the colorbox when validation errors appear. My goal is to activate this function when parsley detects er ...

"jQuery's input type property is not functioning properly when attempting to append new

I am facing an issue with my dynamic table structure and the add row option. Whenever I click on add, a new row is created. However, the problem arises when the $("[name*=vehicle_type]").change(function () does not work for appended input fields. It only ...

When utilizing React router v5, the exact property in a route may not function as expected if there is a

I am attempting to structure routes like Vue.js in an array format: // routes.js export const routing = [ { path: "/setting", component: Setting, }, { path: "/", co ...

Altering the display attribute cancels out any opacity transitions

When using JavaScript to change the opacity of an element with transition: opacity 1s, the expected duration of one second is met, as demonstrated here: onload = e => { var p = document.getElementsByTagName("p")[0]; p.style.opacity = 1; }; p { ...

Styling HTML elements with CSS to create a full width underline effect

Is there a way to make the underlines/borders full width for each line in a paragraph without adding line breaks? I'm seeking suggestions on how to achieve this. Two potential solutions I've considered are using the tag or creating an image, ...

Exploring the Length of an Array with the v-for Directive in Vue.js

https://i.stack.imgur.com/AZipr.png How can I display the total number of students using VueJs? Below is the Grapql API I am working with: query{ allStudents{ totalCount edges{ node{ id lastName email } } ...

Personalize Dropdown Menu, determining when to initiate the hide menu action

When creating a dropdown using ul and li tags, I am faced with the dilemma of determining the ideal time to hide the dropdown menu. The dropdown menu is designed to display values based on user input as they type, updating dynamically. Initially, I had se ...

Switch back to the original CSS when a different button is clicked by the user

I am facing an issue with my jQuery UI accordion where the arrow icons are not behaving as expected. Each header element has a right arrow that changes to a down arrow when clicked to display content, and reverts back to its original form when clicked agai ...

Is there a way to bypass TypeScript decorators and instead use NestJS entities like typical types?

I am trying to find a way to work with TypeScript entities in NestJS without using decorators. Currently, I define my entity like this: import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm'; @Entity() export class User { @PrimaryGe ...

Create automatic transcripts for videos, including subtitles and captions

Are there any tools or plugins available that can automatically create a transcript of a video for website playback? For example, generating captions and subtitles in the English language. ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Error: The Stripe webhook payload must be submitted as either a string or a Buffer

I'm currently working on setting up a subscription system using Stripe. I have mostly followed the code from their documentation, but I keep encountering the following error: Webhook signature verification failed. Webhook payload must be provided as a ...

The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...

Avoid invoking ajax requests (or any other process) from a different event handler (or function)

One issue we're facing is that there are two tabs, with the first tab loading content via ajax1 and the second tab loading content via ajax2. Here's a scenario: Click on the first tab, starting to load ajax content. If you quickly click again wit ...

Is it acceptable to incorporate Node.js modules for utilization in Next.js?

Here's a funny question for you. I am trying to generate UUID in my Next.js project without adding any unnecessary packages. So, I decided to import crypto in my component like this: import crypto from 'crypto'; After importing it, I used i ...

Tips for populating an input field with a variable value

Is there a way to automatically fill an input field with a specific variable value? For instance, if the number is set to 10 and a user clicks a button, can the input field be prepopulated with the number 10? var number = 10; <input type="number"> ...

Utilizing my Vue.js web application to send emails directly to the recipient's inbox rather than being redirected to the spam folder using a separate email

As I delve into email integration for web applications, please bear with me in this learning process... I'm currently working on a website for a budding startup company. The frontend is built using vue.js with the webpack template and includes a cont ...