Transform the API response from a string into an array containing multiple objects

How can I transform a string API response into an array of objects?

When making a GET request, the result is returned as a single long string:

const state = {
    strict: true,
    airports: []
};

const getters = {
    allAirports: (state) => state.airports,
};

const actions = {
    getAirports({ commit }) {
        axios.get('https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat')
            .then(response => {
                commit('SET_AIRPORTS', response.data)
            })
    }
};

const mutations = {
    SET_AIRPORTS(state, airports) {
        state.airports = airports
    }
};

The response looks like this:

1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291,5282,10,"U","Pacific/Port_Moresby","airport","OurAirports" ... 

Instead, I want to split this string into separate objects and append them to the airports array like this:

airports: [
  {
   id: 1,
   name: 'Goroka Airport',
   city: 'Goroka',
   country: 'Papua New Guinea',
   iata: 'GKA',
   icao: 'AYGA',
   longitude: -6.081689834590001,
   latitude: 145.391998291
  },
  {
   etc...
  }
]

Can you provide guidance on how to achieve this transformation?

Answer №1

Give this code a shot, it's been crafted in a clear and concise manner

var WholeData = [1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291,5282,10,"U","Pacific/Port_Moresby","airport","OurAirports",2,"Madang Airport","Madang","Papua New Guinea","MAG","AYMD",-5.20707988739,145.789001465,20,10,"U","Pacific/Port_Moresby","airport","OurAirports"];
var fullarray = WholeData;

var i = 0;
var airportArray = []; 

fullarray.forEach(function callbackFn(value, index) {

  if (typeof airportArray[i] == 'undefined') {
    airportArray[i] = [];
  }
    
  airportArray[i].push(value);
  
  if((index+1)%14==0 && index!=0)
  {
    i++;
  }

});


var j = 0;
var finalArr = [];
airportArray.forEach(function callbackFn(value, index) {
    finalArr.push({
        id: value[0],
        name: value[1],
        city: value[2],
        country: value[3],
        iata: value[4],
        icao: value[5],
        longitude: value[6],
        latitude: value[7],
    });

});


console.log(finalArr);

Answer №2

  1. To extract the individual data lines, utilize String.prototype.split() with \n as the delimiter on the text response fetched from the specified URL.

  2. Employ Array.prototype.map() to transform each line:

    a. Separate the comma-separated values from the line using String.prototype.split() with , as the separator.

    b. Remove unnecessary quotes from the values by employing String.prototype.replace() with a regular expression that matches leading/trailing quotes and replacing them with an empty string.

    c. Create an object with the specified fields.

const actions = {
  getAirports({ commit }) {
    axios
      .get('https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat')
      .then(response => {
        // 1️.
        const lines = response.data.split('\n');
        // 2️.
        const airports = lines.map(line => {
          const fields = line.split(',') // 2a.
                            .map(x => x.replace(/(^"|"$)/g, '')); // 2b.

          // 2c.
          return {
            id: fields[0],
            name: fields[1],
            city: fields[2],
            country: fields[3],
            iata: fields[4],
            icao: fields[5],
            longitude: fields[6],
            latitude: fields[7],
          };
        });

        commit('SET_AIRPORTS', airports);
      })
  }
};

view demo

Answer №3

For a precise measurement of the object's length, consider implementing the following code snippet:

const blueprint = {
   id: '',
   name: '',
   city: '',   
   country: '',
   iata: '',
   icao: '',
   longitude: '',
   latitude: ''
}
const data = [1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291]
let divided = []  //* final result
let chunkSize = 8 //* specified chunk size



for (let i = 0; i< data.length; i+=chunkSize) {
  let object = {}
  let temporary = data.slice(i, i+chunkSize)
  
 
  Object.keys(blueprint).map((key,index)=>{
     object[key] = temporary[index]
  })
  divided = [...divided,object]
}


console.log(divided)

const prototype = {
   id: '',
   name: '',
   city: '',   
   country: '',
   iata: '',
   icao: '',
   longitude: '',
   latitude: ''
}
const arr = [1,"Goroka Airport","Goroka","Papua New Guinea","GKA","AYGA",-6.081689834590001,145.391998291]
let chunked = []  //* final  output
let chunk = 8 //* chunk length



for (let i = 0; i< arr.length; i+=chunk) {
  let obj = {}
  let temp = arr.slice(i, i+chunk)
  
 
  Object.keys(prototype).map((key,i)=>{
     obj[key] = temp[i]
  })
  chunked = [...chunked,obj]
}


console.log(chunked)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

Leveraging react-markdown alongside Material-UI's table component

Currently, I am attempting to parse a markdown table using the react-markdown library and then displaying the resulting tags with the help of the Material-UI table component. Below is the code snippet for my renderer: import withStyles from '@material ...

The size of the array within the object does not align

I've run into a roadblock while attempting to implement the tree hierarchy in D3. Initially, I believed that I had correctly structured the JSON data, but upon inspecting the object using Developer's Tool, a discrepancy caught my eye: https://i. ...

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Use the filter method to organize arrays into subarrays based on their length, filtering out those with a length greater than or

Hey there, I've been working on incorporating the array filter property to separate subarrays that are greater than and less than 3 into two distinct functions. Unfortunately, I'm a bit stuck on how to continue fixing my functions. Can someone pr ...

Error code 1 occurs when attempting to execute the "npm run start" command

Every time I attempt to execute "npm run start" within my project folder, the following error message pops up: myLaptop:app-name userName$ npm run start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a0b1b1ecafa0aca481f ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

An alternative solution for supporting Edge Chromium is utilizing synchronous AJAX requests within the beforeunload event

While attempting a synchronous ajax request during the beforeunload event, I encountered an error stating that synchronous ajax requests are not supported in chromium browsers during page unload events. I am seeking alternatives for making a synchronous a ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Troubleshoot: Unable to utilize mapActions with Vuex modules

Having trouble using mapActions to reference actions in my modules. The Vuex docs say that module actions are not namespaced by default, so they should be accessible like main store actions. Here's how I have things set up: Store import * as ModuleA ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

Use $.ajax to display the menu by capturing an array of elements {0}

Whenever I click on one of the DIV elements, a menu pops out on the side displaying more information about the clicked element. I can determine which element I'm clicking on, but I'm struggling to pass that information from jQuery to the PHP pag ...

Having trouble extracting data from a particular cell within an HTML table using jQuery

I am struggling to extract row data from a table for utilization in a modal. Provided below is my code for Views. <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css"> <link href="@Url.Content(" ...

I must arrange each item in a column vertically, regardless of whether they could align horizontally

As the title suggests, I am looking for a way to stack one element under another, similar to a chat application. Currently, when the message is long, it displays correctly, but if the text fits next to each other, it aligns in that manner. I require a solu ...

Tips for effectively utilizing Vuex to manage items within a Vuetify data table

I am currently sending an API request to retrieve an array of objects that has the following structure: returnedItems [ { name: 'Adam', age: '30', interest: 'Sports' }, ...

What is the best way to transfer a user-generated PNG file to my backend server?

I'm in the process of developing a website that enables users to generate personalized graphics and easily download them directly from the platform. My approach involves allowing users to customize an svg using a javascript-powered form, which is the ...

Transfer PDF file to user's web browser through XMLHttpRequest, utilizing up-to-date HTML5 techniques, all while maintaining the integrity of the document's encoding

I am trying to achieve a similar result as described in this StackOverflow post about handling file download from ajax post. However, I'm working with a dynamically-generated PDF file created using PHP v5.6.10 (with the PDFLib extension, v9.0.5). Unf ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...

Store the information from an AJAX post request in a div element into the browser

I've set up a datatable with a button that posts data into a div. Below is the HTML code I used: HTML : <div class="card-body"> <div class="overlay" id="kt_datatable_nodata"> <div class="o ...