Home > database >  Parse/Display nested JSON array with Jquery
Parse/Display nested JSON array with Jquery

Time:05-17

I am looking to pull data from a job board API. I'd like to have headings for the departments (pulled from JSON level 1) and under each department the current open positions (JSON level 2). I have tinkered with this 50 different ways and ran through all the related articles I can find, but just can't quite get the dominoes to fall in my brain.

Update

I have gotten pretty close, but I'm obviously missing how to loop this correctly. It repeats every department and job instead of nesting all of the jobs under the department header once.

Fiddle to see where I am at - https://jsfiddle.net/swampfox/f6jv204x/#&togetherjs=GjcUL090zr

$(function() {
  $.ajax({
    url: 'https://boards-api.greenhouse.io/v1/boards/agilityrobotics/departments',
    data: {
      check: 'one'
    },
    dataType: 'jsonp',
    success: function(result) {
      $.each(result, function(key, value) {
        for (var i = 0; i < value.length; i  ) {
          $.each(value[i].jobs, function(k, v) { // Second Level into Jobs
            $('#jsonpResult').append(
              $('<h3>'   value[i].name   '</h3><p ><a  href="'   v.absolute_url   '"> '   v.title   '</a></p>')
            );
          });
        }
      });
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="jsonpResult"></div>

CodePudding user response:

The main issue is that you output the h3 for each job, but it should only be output once per iteration of the outer loop (not the inner loop).

I would also use more jQuery style for creating the elements, and I would use async/await to flatten a bit the "callback hell".

$(async function() {
    let {departments} = await $.getJSON('https://boards-api.greenhouse.io/v1/boards/agilityrobotics/departments');
    $("#jsonpResult").append(
        departments.flatMap(({name, jobs}) => [
            $("<h3>").text(name),
            ...jobs.map(({absolute_url: href, title}) =>
                $("<p>", { "class": "cat" }).append(
                    $("<a>", { href, "class": "joblink" }).text(title)
                )
            )
        ])
    );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="jsonpResult"></div>

  • Related