Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda