I am writing a axios JSON data call function and want to push values from my jJSON function to use outside of the function. Is there anyways I can do that?
My Code:
let website_names = `${api}`;
axios.get(website_names, {
cancelToken: new CancelToken(function executor(c) {
api_requests.website_nm = c;
})
})
.then(function(website_name) {
website_name.data.forEach(d => {
let yoyo = [];
yoyo.push(d.element);
console.log(yoyo);
});
}).catch(function(error) {
console.log(error);
alert_error(error);
});
This one gives me:
- {element: “Google”}
- {element: “Yahoo”}
- {element: “Facebook”}
- {element: “BuzzFeed”}
- {element: “Cnet”}
I need yoyo = ["Google", "Yahoo", "Facebook", "BuzzFeed", "Cnet"]
But I also need to use yoyo
outside of the axios function. I need the use of the array after it has been formed inside of axios.
2
Answers
You can use
map
for this:You’re creating a new array in each iteration thereby destroying the previous. The array should be initialized outside the
forEach
loop: