Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Dynamically add values from different json responses - JS

I am calling an API and getting the total_tweet_count. If the meta tag contains a next_token, I fetch the next API (here I call the corresponding object) with the next_token and push the total_tweet_count to an array. However, if the response doesnt contain a next_token, I stop iterating and just push the total_tweet_count and return the array. For some reason, the code doesnt seem to run. Please help.

The below example should get the next_token from res1 and call res2 and push the tweet_count into the array. Then using the next_token of res2, fetch res3 data and push the count. Since res3 doesnt have a next_token, we end the loop and return the data. This is the expectation. Please advice.

const getData = async () => {
  const totalCount = [];
  const results = await Promise.resolve(data.res1);
  totalCount.push(results.meta.total_tweet_count)
  do {
    const results1 = await Promise.resolve(data[`res${results.meta.next_token}`]);
    totalCount.push(results1.meta.total_tweet_count)
  }
  while (results.meta.next_token)
  return totalCount;
}

getData().then(res => console.log(res))

The final output I expect is [1,20, 8]

Please advice.

Fiddle Link: https://jsfiddle.net/czmwtj3e/

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your loop condition is constant:

  const results = await Promise.resolve(data.res1);
//^^^^^^^^^^^^^
  …
  do {
    …
  }
  while (results.meta.next_token)

What you are looking for is

const getData = async () => {
  const totalCount = [];
  let results = await Promise.resolve(data.res1);
  totalCount.push(results.meta.total_tweet_count)
  while (results.meta.next_token) {
    results = await Promise.resolve(data[`res${results.meta.next_token}`]);
    totalCount.push(results.meta.total_tweet_count)
  }
  return totalCount;
}

or

const getData = async () => {
  const totalCount = [];
  let results = {meta: {next_token: 1}};
  do {
    results = await Promise.resolve(data[`res${results.meta.next_token}`]);
    totalCount.push(results.meta.total_tweet_count)
  }
  while (results.meta.next_token)
  return totalCount;
}

Notice there is no const results1 in either of these, but an assignment to the mutable results variable.

about 4 years ago · Juan Pablo Isaza Report

0

As far as I can tell:

  • getData() is a wholly synchronous process acting on data therefore does not need to be an asyncFunction.
  • the required array of tweet counts can be created with a combination of Object.keys() and Array.prototype.reduce().
  • the .next_token property does not need to be used (unless it has some secret meaning beyond what has been explained in the question).
const getData = () => {
    const keys = Object.keys(data); // array ['res1', 'res2',  'res3'] 
    const totalCounts = keys.reduce((arr, key) => { // iterate the `keys` array with Array.prototype.reduce()
        arr.push(data[key].meta.total_tweet_count); // push next tweet count onto the array
        return arr; // return `arr` to be used in the next iteration
    }, []); // start the reduction with empty array
    return totalCounts; // [1, 20, 8]
};

In practice, you would:

  • pass data to the function
  • avoid intermediate variables
    const getData = (data) => {
        return Object.keys(data).reduce((arr, key) => {
            arr.push(data[key].meta.total_tweet_count);
            return arr;
        }, []);
    };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!