Filter nested API response data to output json

Viewed 75

An API endpoint at https://api.spacexdata.com/v3/launches/past returns data. I need to filter through that data to display a json on the screen that would only contain the API data entries with "DARPA" in the customers field and "2017" in the launch_year one. The customers and payloads fleids are arrays of arbitrary length.

The response data first entry looks like this. A number of its fields are omitted. Please visit the API link to see the full response.

0   
  flight_number 1
  mission_name  "FalconSat"
  upcoming  false
  launch_year   "2006"
  launch_date_unix  1143239400
  launch_date_utc   "2006-03-24T22:30:00.000Z"
  launch_date_local "2006-03-25T10:30:00+12:00"
  is_tentative  false
  tentative_max_precision   "hour"
  tbd   false
  launch_window 0
  rocket    
    rocket_id   "falcon1"
    rocket_name "Falcon 1"
    rocket_type "Merlin A"
    first_stage {…}
    second_stage    
      block 1
      payloads  
        0   
          payload_id    "FalconSAT-2"
          norad_id  []
          reused    false
          customers 
            0   "DARPA"

How do I go about it?

2 Answers

Here you go:

<?php
$data = json_decode(file_get_contents('https://api.spacexdata.com/v3/launches/past'), true);
foreach($data as $entry) {
   if($entry['launch_year'] === '2017') {
      if(isset($entry['rocket']['second_stage']['payloads'])) {
         foreach($entry['rocket']['second_stage']['payloads'] as $payload) {
            foreach($payload['customers'] as $customer) {
               if($customer === 'DARPA') print_r($entry);
            }
         }
      }
   }
}

You will need to add some error handling on your own. Code works, but there are no DARPA customers in 2017. If you check 2006 then it will found it.

Here you go

fetch('https://api.spacexdata.com/v3/launches/past')
  .then(res => res.json())
  .then(response => {
    const res = response.filter(
      x =>
        x.launch_year === '2007' && x.rocket.second_stage.payloads.some(payload => payload.customers.includes('DARPA'))
    );
    console.log(res);
  });

Related