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

149
Views
More Concise/Elegant Way to Concat JSON Elements Returned by fetch()

I'm currently fetching categories from WordPress using REST. The 100 limit forced me to do multiple queries. Here is my current function for this. It's not pretty. Can anyone come up with something more concise?

export async function getAllCategories() {
    let arr = []
    const res = await fetch(`${API_URL}wp/v2/categories?per_page=100&page=1`)
    const data = await res.json()
    const totalPages = res.headers.get("X-WP-TotalPages")
    data.forEach((el) => {
        arr.push(el)
    })
    let i = 2
    while (i <= totalPages) {
        const res = await fetch(`${API_URL}wp/v2/categories?per_page=100&page=${i}`)
        const data = await res.json()
        data.forEach((el) => {
            arr.push(el)
        })
        i++
    }
    return arr
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could define a secondary function getCategories which retrieves the categories for the specific page and the total number of pages.
This will remove the fetch call duplication.
Also, you can use the spread operator to avoid the forEach loops to populate the resulting array:

export async function getAllCategories() {
    let result = []
    let page = 1;
    let totalPages = 0;
    do  {
        const { data, total } = await getCategories(page);
        result.push(...data)
        totalPages = total
        page++
    } while (page <= totalPages);
    return result
}

const getCategories = async (page) => {
    const res = await fetch(`${API_URL}wp/v2/categories?per_page=100&page=${page}`)
    return {
        data: await res.json(),
        total: res.headers.get("X-WP-TotalPages")
    }
}
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!