<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: J.S.</title>
    <description>The latest articles on Forem by J.S. (@jspeda).</description>
    <link>https://forem.com/jspeda</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F17059%2F815bcea2-9b46-4aab-b9c4-804e51c9f632.jpeg</url>
      <title>Forem: J.S.</title>
      <link>https://forem.com/jspeda</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/jspeda"/>
    <language>en</language>
    <item>
      <title>Using fetch() and reduce() to grab and format data from an external API - A practical guide</title>
      <dc:creator>J.S.</dc:creator>
      <pubDate>Wed, 03 May 2017 18:39:18 +0000</pubDate>
      <link>https://forem.com/jspeda/using-fetch-and-reduce-to-grab-and-format-data-from-an-external-api---a-practical-guide</link>
      <guid>https://forem.com/jspeda/using-fetch-and-reduce-to-grab-and-format-data-from-an-external-api---a-practical-guide</guid>
      <description>&lt;p&gt;Today we’re going to learn how to get and manipulate data from an external API. We’ll use a practical example from one of my current projects that you will hopefully be able to use as a template when starting something of your own.Â &lt;br&gt;
For this exercise, we will look at current job posting data for New York City agencies. New York City is great about publishing &lt;a href="https://opendata.cityofnewyork.us/" rel="noopener noreferrer"&gt;all sorts of datasets&lt;/a&gt;, but I chose this particular one because it doesn’t require dealing with API keysâ€Š–â€Šthe endpoint is a publicly accessible URL.&lt;/p&gt;

&lt;p&gt;Here’s  a quick roadmap of of our plan. We’ll get the data from New York City’s servers by using JavaScript’s Fetch API, which is a good way to start working with &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noopener noreferrer"&gt;promises&lt;/a&gt;. I’ll go over the very bare basics here, but I recommend Mariko Kosaka’s excellent illustrated blog &lt;a href="http://kosamari.com/notes/the-promise-of-a-burger-party" rel="noopener noreferrer"&gt;&lt;em&gt;The Promise of a Burger Party&lt;/em&gt;&lt;/a&gt; for a more thorough (and delicious) primer.Â &lt;/p&gt;

&lt;p&gt;If you’ve ever used &lt;code&gt;$.getJSON()&lt;/code&gt; in jQuery, you’re mostly there conceptually. If not, that’s okay, too. Take a look at the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cityJobsData = fetch("https://data.cityofnewyork.us/resource/swhp-yxa4.json");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We declare a variable, &lt;code&gt;cityJobsData&lt;/code&gt;, and set its value to &lt;code&gt;fetch(the URL that contains the data we want)&lt;/code&gt; which returns something called a promise. For now, just think of it as the the data we will &lt;em&gt;eventually&lt;/em&gt; get back from the URL when the request is complete. We can access and manipulate this data once it loads by subsequently calling &lt;code&gt;then()&lt;/code&gt; on &lt;code&gt;cityJobsData&lt;/code&gt;. To perform multiple operations, we can chain &lt;code&gt;then()&lt;/code&gt;s together, making sure we 1. always pass in our data as an argument to the callback, and 2. return a value.Â&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cityJobsData = fetch("https://data.cityofnewyork.us/resource/swhp- yxa4.json");
cityJobsData
  .then(data =&amp;gt; data.json())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above snippet, we’re telling the computer to execute everything contained inside &lt;code&gt;then()&lt;/code&gt; &lt;em&gt;once the data is retrieved from the URL&lt;/em&gt;. This is what we call â€˜asynchronous’ code. In this case, &lt;code&gt;.then(data =&amp;gt; data.json())&lt;/code&gt; returns the data in JSON format, which will allow us to operate on it.&lt;/p&gt;

&lt;p&gt;Just a quick aside for wrangling huge amounts of JSON: If you go in your web browser to the &lt;a href="https://data.cityofnewyork.us/resource/swhp-yxa4.json" rel="noopener noreferrer"&gt;URL that contains the data we want&lt;/a&gt;, you’ll see an enormous, unformatted block of text that is very hard to read. However, you can copy and paste that text into something like &lt;a href="http://jsonviewer.stack.hu" rel="noopener noreferrer"&gt;jsonviewer&lt;/a&gt;, which will give you an organized, hierarchical, overview of the contents. Let’s say we want to see how many postings there are for each city agency. How can we do this? Well if we look at our JSON schema in this viewer, we can see that it’s an array of objects, with each object containing all the data that makes up a single job posting.Â &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpuu.sh%2FvEskM%2Fbfc135fe16.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fpuu.sh%2FvEskM%2Fbfc135fe16.png" alt="formatted JSON"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note that each object contains a key, &lt;code&gt;agency&lt;/code&gt;, whose value is the name of the city agency that has a job available.Â &lt;/p&gt;

&lt;p&gt;Therefore, if we can somehow keep track of how many times each agency is mentioned throughout this array of objects, we’ll be able to know how many jobs are currently available per agency.Â &lt;/p&gt;

&lt;p&gt;How can we do this? One way is to use &lt;code&gt;reduce()&lt;/code&gt;. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=example" rel="noopener noreferrer"&gt;From MDN&lt;/a&gt;, “The &lt;code&gt;reduce()&lt;/code&gt; method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.” If this sounds like a bunch of nonsense to you, don’t worry! We’ll see soon that it’s not so bad when we have some examples to work through.&lt;/p&gt;

&lt;p&gt;Most introductions to &lt;code&gt;reduce()&lt;/code&gt; involve simple addition, which is a fine starting point. Let’s walk through this example together: Â&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = [1, 2, 4, 6];
const added = arr.reduce((accumulator, item) =&amp;gt; {
 return accumulator + item;
}, 0);

console.log(added); // 13
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s how it works: the &lt;code&gt;reduce()&lt;/code&gt; function loops through the array, &lt;code&gt;arr&lt;/code&gt;, and adds each &lt;code&gt;item&lt;/code&gt; to an accumulator, which has an initial value of &lt;code&gt;0&lt;/code&gt; (we make this value &lt;code&gt;reduce()&lt;/code&gt;'s second argument, after the callback function). The accumulator’s current value is returned at the end of every loop, which is how the adding happens. Thus, the final value of &lt;code&gt;added&lt;/code&gt; is 13.Â &lt;/p&gt;

&lt;p&gt;If you’re having trouble visualizing this, try adding a &lt;code&gt;console.log()&lt;/code&gt; statement before your return that outputs the current values of the accumulator and the itemâ€Š–â€Šthis way, you’ll be able to see the looping that’s happening behind the scenes. Here’s a set of log statements for the above example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;adding 1 to accumulator: 0
adding 2 to accumulator: 1
adding 4 to accumulator: 3
adding 6 to accumulator: 7
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is all well and good, and it’s fun to do some addition with &lt;em&gt;~*functional programming&lt;/em&gt;~*, but did you know &lt;code&gt;reduce()&lt;/code&gt; can do more than simply count things? And that the accumulator can be something other than a number?Â It's true!&lt;/p&gt;

&lt;p&gt;In our case, we’ll use it to find out how many current job postings there are per New York City agency. This might seem like a big leap from simply adding numbers together, but the core concepts of looping and accumulating are the same.Â &lt;/p&gt;

&lt;p&gt;This time, instead of reducing an array of four numbers, we want to reduce our JSON blob of job posting data. And instead of reducing to a single number, we’re going to reduce to a single object. Yes, an object! Once the function is completed, the accumulator object’s keys will be the names of the city agencies and the keys’ values will be the number of postings they have, like this: &lt;code&gt;{"name of agency": number of job postings}&lt;/code&gt;. Here’s the whole program:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cityJobsData = fetch("https://data.cityofnewyork.us/resource/swhp-yxa4.json");
cityJobsData
  .then(data =&amp;gt; data.json())
  .then(data =&amp;gt; {
    const agencyFrequency = data.reduce((agencies, value) =&amp;gt; {
      agencies[value.agency] = agencies[value.agency] ? agencies[value.agency] + 1 : 1;
      return agencies;
    }, {});
    console.log(agencyFrequency);
  })
  .catch(err =&amp;gt; console.log(err));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How does this work, exactly? Let’s break it down. Each time around the loop, we’re looking at a specific &lt;code&gt;value&lt;/code&gt;, i.e., one object in &lt;code&gt;data&lt;/code&gt;, our aforementioned array of objects. We’re checking to see if a key with the name of the current agency (&lt;code&gt;value.agency&lt;/code&gt;) already exists within our accumulator object. If not, we add it to the accumulator object and set its value to 1. If a key with the name of the current agency &lt;em&gt;already exists within the accumulator object&lt;/em&gt;, we add 1 to its existing value. We return the accumulator object when we’re done and get this nice set of data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ 
  'FIRE DEPARTMENT': 17,
  'DEPT OF ENVIRONMENT PROTECTION': 134,
  'DEPARTMENT OF INVESTIGATION': 22,
  'DEPARTMENT OF SANITATION': 14,
  'DEPT OF HEALTH/MENTAL HYGIENE': 247,
  'OFFICE OF THE COMPTROLLER': 14,
  'ADMIN FOR CHILDREN\'S SVCS': 43,
  'DEPT OF DESIGN &amp;amp; CONSTRUCTION': 48,
  'ADMIN TRIALS AND HEARINGS': 16,
  'DEPT OF PARKS &amp;amp; RECREATION': 34,
  'HUMAN RIGHTS COMMISSION': 4,
  'POLICE DEPARTMENT': 36,
  'DEPT OF INFO TECH &amp;amp; TELECOMM': 50,
  'DISTRICT ATTORNEY KINGS COUNTY': 4,
  'TAXI &amp;amp; LIMOUSINE COMMISSION': 11,
  'HOUSING PRESERVATION &amp;amp; DVLPMNT': 21,
  'DEPARTMENT OF BUSINESS SERV.': 18,
  'HRA/DEPT OF SOCIAL SERVICES': 31,
  'DEPARTMENT OF PROBATION': 3,
  'TAX COMMISSION': 4,
  'NYC EMPLOYEES RETIREMENT SYS': 6,
  'OFFICE OF COLLECTIVE BARGAININ': 2,
  'DEPARTMENT OF BUILDINGS': 9,
  'DEPARTMENT OF FINANCE': 29,
  'LAW DEPARTMENT': 21,
  'DEPARTMENT OF CORRECTION': 12,
  'DEPARTMENT OF TRANSPORTATION': 67,
  'DEPT OF YOUTH &amp;amp; COMM DEV SRVS': 5,
  'FINANCIAL INFO SVCS AGENCY': 7,
  'CULTURAL AFFAIRS': 1,
  'OFFICE OF EMERGENCY MANAGEMENT': 12,
  'DEPARTMENT OF CITY PLANNING': 5,
  'DEPT OF CITYWIDE ADMIN SVCS': 15,
  'DEPT. OF HOMELESS SERVICES': 3,
  'DEPARTMENT FOR THE AGING': 2,
  'CONSUMER AFFAIRS': 7,
  'MAYORS OFFICE OF CONTRACT SVCS': 7,
  'DISTRICT ATTORNEY RICHMOND COU': 3,
  'NYC HOUSING AUTHORITY': 9,
  'CIVILIAN COMPLAINT REVIEW BD': 5,
  'OFF OF PAYROLL ADMINISTRATION': 1,
  'EQUAL EMPLOY PRACTICES COMM': 1 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Et Voila&lt;/em&gt;! We now know that if we want to work for the City government, we should check out the Department of Health and Mental Hygiene’s 247 openings!&lt;/p&gt;

&lt;p&gt;We can do a bunch of useful things with this data â€Š– â€Špersonally, I want to dip my toes into data visualization, so I’ll be using it to make a simple chart. I hope you’ll be able to use this example as a jumping-off point for your own projects.&lt;br&gt;
If you enjoyed this article, please reach out to me on &lt;a href="https://twitter.com/j_speda" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href="https://twitter.com/jimcodes" rel="noopener noreferrer"&gt;Jim O’Brien&lt;/a&gt; for editing.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>promises</category>
      <category>reduce</category>
      <category>learning</category>
    </item>
    <item>
      <title>Hi, I'm J.S.</title>
      <dc:creator>J.S.</dc:creator>
      <pubDate>Wed, 19 Apr 2017 20:49:04 +0000</pubDate>
      <link>https://forem.com/jspeda/hi-im-js</link>
      <guid>https://forem.com/jspeda/hi-im-js</guid>
      <description>&lt;p&gt;I live in New York City and currently work as an attorney. I have been coding for about a year, mostly in JavaScript. I'm currently learning about React, functional programming, algorithms, and the process of habit forming.&lt;/p&gt;

&lt;p&gt;You can find me on GitHub as &lt;a href="https://github.com/jspeda" rel="noopener noreferrer"&gt;jspeda&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nice to meet you. :)&lt;/p&gt;

</description>
      <category>introduction</category>
    </item>
  </channel>
</rss>
