run_time_error
run_time_error

Reputation: 707

How to map object to Array in ES6?

I have an array of objects called 'urls' containing object each having 'name' and 'url' property. I want to map each object to an array. How can I achieve this ?

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);
        });
});

Here res.data.payload will be an array of object, axiosData is defined in data inside the property of Vue instance. I want 'axiosData' which is an array to be an array of array of objects.

The axiosData might be 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,

}]]

Upvotes: 0

Views: 210

Answers (1)

longroad
longroad

Reputation: 405

You should use Promise.all function in order to make multiple requests.

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;
})

Upvotes: 2

Related Questions