skip to Main Content

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


  1. You can use map for this:

    const getWebsites = () => {
      let website_names = `${api}`;
    
      return axios
        .get(website_names, {
          cancelToken: new CancelToken(function executor(c) {
            api_requests.website_nm = c;
          })
        })
        .then(function(website_name) {
          return website_name.data.map(d => d.element);
        })
        .catch(function(error) {
          console.log(error);
          alert_error(error);
        });
    };
    
    getWebsites().then(yoyo => {
      //you now have the array
    });
    Login or Signup to reply.
  2. You’re creating a new array in each iteration thereby destroying the previous. The array should be initialized outside the forEach loop:

    let yoyo = [];
    website_name.data.forEach(d => {
       yoyo.push( d.element );
    });
    console.log(yoyo);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search