0

I'm trying to manipulate JSON data received from an API url (this is my first time handling this type of work)

The following function returns a promise of a 20 element array:

const articles = () => {
return fetch(url)
.then(res => res.json())
.then(post => post.articles);
};

Console view:

enter image description here

Now, I'd like to extract the elements from the array - I tried something like:

articles()[0].name

but this doesn't work and I'm not sure of an alternative way to go about this? Appreciate your help. Thanks

Jat90
  • 493
  • 1
  • 10
  • 22
  • Try to define variable and then assign the returned response to that variable! – Prashant Pimpale Aug 19 '18 at 15:34
  • 1
    Once you've parsed it (`response.json()`), it's not JSON, it's just an array. JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Aug 19 '18 at 15:34

1 Answers1

2

Your articles fucntion returns a promise. You have to consume the promise (more on MDN):

articles().then(articleArray => {
    console.log(articleArray);
});

or within an async function:

const articleArray = await articles();
console.log(articleArray);

Side note: Your fetch code is missing a check for HTTP success (HTTP failure isn't a rejection). You're by far not the only person who misses out this check, so much so that I've written a post on my anemic blog about it. With the check:

const articles = () => {
    return fetch(url)
    .then(res => {
        if (!res.ok) {
            throw new Error("HTTP error " + res.status);
        }
        return res.json();
    })
    .then(post => post.articles);
};
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks - noted on the HTTP success check. Rather than printing the array list to console, is it possible to store the received array as a separate array variable? This way I can easier manipulate it like array[0].author etc. I did try to assign articles().then(res => res) to array variable but it still returned the promise – Jat90 Aug 19 '18 at 16:18
  • @Jat90 - You can do that, but in general it doesn't make sense to. Just use the array within the `then` callback. If you save it to some variable the `then` callback closes over, at some point you **are** going to try to use it before the ajax call has completed, see [this question's answers](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) for more on that point. – T.J. Crowder Aug 19 '18 at 16:22