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
Changing json object property from inside fetch using another fetch

I am creating a web application using the REST Countries API (link given) https://restcountries.com/.
The API gives json with the property borders, which is an array of strings giving the cca3 of the bordering countries. I would like to get the names of the countries too and so am making another request for that data. So far this is what I have come up with. But, the json returned from the first request is never changed. I don't know what is going on, if anybody could advice?

const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', (req, res, next) => {
    const code = req.params.code
    fetch(`${dataAPI}/alpha/${code}?fields=borders`)
        .then(response => response.json())
        .then(json => fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`))
        .then(response => response.json())
        .then(bordersJson => {
            fetch(`${dataAPI}/alpha/${code}`)
                .then(response => response.json())
                .then(data => {
                    data.borders = bordersJson
                    res.send(data)
                }).catch(err => next(err))
        }).catch(err => next(err))
})
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Async/await is a better approach for this case.

  const dataAPI = 'https://restcountries.com/v3.1/'
    router.get('/country/:code', async (req, res, next) => {
        try {
            const code = req.params.code;
        const borderJSON = await fetch(`${dataAPI}/alpha/${code}?fields=borders`).then(response => response.json());
        // response:  {"borders":["BGD","BTN","MMR","CHN","NPL","PAK"]}
        const codes = borderJSON.borders.join(',');
        const cca3 = await fetch(`${dataAPI}/alpha?codes=${codes}&fields=cca3,name`)).then(response => response.json());
        //  [{"name":{...},"cca3":"BGD"},{"name":{...},"cca3":"PAK"}]
        res.send(cca3);
        } catch (err) {
            next(err);
        }
    
    });
over 4 years ago · Santiago Trujillo Denunciar

0

The reason the borders property was not replaced was that the API endpoint used returns an array with one object, not the object itself. Also, I found that finding the borders separately was unnecessary.

Final Solution

router.get('/country/:code', (req, res, next) => {
    const code = req.params.code
    fetch(`${dataAPI}/alpha/${code}`)
        .then(response => response.json())
        .then(json => {
            json = json[0]
            fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`)
                .then(response => response.json())
                .then(bordersJSON => {
                    json.borders = bordersJSON
                    res.send(json)
                }).catch(err => next(err))
        }).catch(err => next(err))
})
over 4 years ago · Santiago Trujillo 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