0

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,

}]]
6
  • Kind of unclear... what's an example of your desired data structure? Commented Dec 12, 2018 at 6:18
  • @robinsax axiosData might be like this [ [ obj1, obj2, obj3....], [another_obj1, another_obj2, another_obj3, ....], ..... ] Commented Dec 12, 2018 at 6:22
  • with the objects containing what? Commented Dec 12, 2018 at 6:25
  • why not use push if you just want to push the array url objects to axiosData Commented Dec 12, 2018 at 6:26
  • @robinsax I have edited the question hope now its clear, Commented Dec 12, 2018 at 6:34

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

works like a charm, but I could not understand why this works. looks like I have to revisit pormise. thanks btw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.