简体   繁体   中英

How do I select the data I need from this api?

I am trying to connect this public API to my website. I got it working, but it gives me all the "buy" and "sell" data. When in reality I only want to obtain the purchase and sale data of the blue dollar, official dollar, dollar counted with liquid, dollar bag, solidarity dollar.

Use the following code with fetch:

function fetchData() {
    fetch("https://www.dolarsi.com/api/api.php?type=valoresprincipales")

    .then(response => {
        return response.json();
    })
    .then(data => {
        console.log(data);
        const html = data
        .map(user => {
           
            return `
            <div class="user">
                <p>Compra: ${user.casa.compra}</p>
                <p>Venta: ${user.casa.ventas}</p>

          </div>
          `;
        })
        .join("");
        console.log(html);
        document
        .querySelector('#price')
        .insertAdjacentHTML("afterbegin", html); 

    });


}

fetchData();

Try like this:

 function fetchData() { fetch("https://www.dolarsi.com/api/api.php?type=valoresprincipales") .then(response => { return response.json(); }) .then(data => { console.log(data); const html = data .map(user => { if(["Dolar Blue", "Dolar Oficial", "Dolar Contado con Liqui", "Dolar Bolsa"].indexOf(user.casa.nombre) !== -1) { return ` <div class="user"> <p>Compra: ${user.casa.compra}</p> <p>Venta: ${user.casa.venta}</p> </div> ` } else { return ''; }; }) .join(""); console.log(html); document .querySelector('#price') .insertAdjacentHTML("afterbegin", html); }); } fetchData();
 <div id="price"></div>

Using an if condition inside the map function will allow you to filter the data to what you're looking for. By creating an array of the names you are interested in, you can only include results which have names you listed.

This is my solution:

 function fetchData() { fetch("https://www.dolarsi.com/api/api.php?type=valoresprincipales") .then(response => { return response.json(); }) .then(data => { const filteredOutput = data.filter(item => { switch (item.casa.nombre) { case "Dolar Blue": case "Dolar Oficial": return item; break; default: return null; } }) let html = ""; filteredOutput.forEach(item => { html += "<div class=\\"user\\">"; html += "<p>"+item.casa.compra + "</p>"; html += "<p>Venta:" + item.casa.venta + "</p>"; html += "</div>"; }) document .querySelector('#price') .insertAdjacentHTML("afterbegin", html); }); } fetchData();
 <div id="price"></div>

For the different value of nombre, you can add more filter in the switch-case loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM