简体   繁体   中英

How to structure a JSON call

I have an endpoint which I call with Axios and the response looks like (for example):

items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},

...and so on.

If I go to one of the url:s in the browser the structure of the JSON is:

fooBar: {
    url: "https://api.foo...",
    id: "123",
    type: "INDEX",
    source: "Foobar",
    quotes: {
        url: "https://api.bar..."
    }
},

I need to get the quotes of the two first url:s in items:[] dynamically because they will disappear when the 'expirationDate' is older than today's date. How can this be achieved? Thanks in advance!

If I understand the requirements correctly you need to:

  • get the list of items
  • get item details for first two items (to extract links to quotes)
  • get quotes for first two items

You can use promise chaining to execute these operations maintaining the order:

const getQuotes = (item) => axios.get(item.url)
  .then(resp => axios.get(resp.data.fooBar.quotes.url));

axios.get('/items') // here should be the url that you use to get items array
  .then(resp => resp.data.slice(0, 2).map(getQuotes))
  .then(quotes => Promise.all(quotes))
  .then(quotes => {
    console.log(quotes);
  });

Please find my proposal below. I gave two examples. You can get the whole quotes object, or just the URL inside the quotes object. This is just a console log, but you can easily ie. append this data to a div in the html or pass this URL to some other function.

$(function() {
  const address = 'https://api.example1...';

  function loadQuotes() {
    $.ajax({
      url: address,
      dataType: 'json',
    }).done(function(response) {
      response.forEach(el => {
        console.log(`el.quotes`);
        // or if you want to be more specific console.log(`el.quotes.url`);
      });
    });
  }

  loadQuotes();
});

If these are nested objects, just append fooBar .

For example change the .done part to:

.done(function(response) {
let qqq = response.quotes
      quotes.forEach(el => {
        console.log(`el.quotes`);
        // or if you want to be more specific console.log(`el.quotes.url`);
      });

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