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

Completing the final touches on my jQuery typing enhancement feature

Currently, I have a code snippet that creates <li> elements with specific dimensions and background images when a user presses a key. The corresponding CSS class is applied to the generated <li>, displaying a specific character on the screen. H ...

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

js The correct value is not being set to the div's style.top

function gamestart(){ var gr; var gr = true; console.log(gr==true); if(gr == true){ console.log("we have activated pointer key detection dear Mr.ketsebaot") document.onkeydown = checkk; } } function checkk(e){ cons ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

Facing some unexpected issues with integrating Django and AngularJS, unclear on the cause

In my simple Angular application, I encountered an issue. When I run the HTML file on its own in the browser, the variable name "nothing" is displayed as expected. However, once I integrate the app into Django by creating a dummy view that simply calls a t ...

Tips for changing array items into an object using JavaScript

I am working with a list of arrays. let arr = ["one","two"] This is the code I am currently using: arr.map(item=>{ item }) I am trying to transform the array into an array of sub-arrays [ { "one": [{ ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

Incorporate a Vue.js computed property into the data retrieved from a server

Coming from Knockout.js, where observables are easily created by defining them, I'm curious if there's a similar approach in Vue.js. let vm = { someOtherVar: ko.observable(7), entries: ko.observableArray() }; function addServerDataToEnt ...

Protecting your Single Page Application with a CSRF token

Utilizing Vue js for the SPA and Laravel for the backend has been smooth so far, but after submitting a form, I've encountered an issue with the csrf token not refreshing. As a result, whenever I attempt to submit another form, it triggers a TokenMism ...

A comparison of Vue's import paths: exploring the variations

Exploring the world of Vue has been exciting but I'm a bit puzzled by the syntax used for importing different libraries. Take, for instance, this import statement: import Vue from 'vue'; import axios from 'axios'; Where do these r ...

Spin a Material UI LinearProgress

I'm attempting to create a graph chart using Material UI with the LinearProgress component and adding some custom styling. My goal is to rotate it by 90deg. const BorderLinearProgressBottom = withStyles((theme) => ({ root: { height: 50, b ...

Prevent incorrect data input by users - Enhancing JavaScript IP address validation

I have been trying to create a masked input field for entering IP addresses, but every solution I come across seems to have some flaws. The best solution I found so far is , but it still allows values higher than 255 to be entered. It works fine initially ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

The URL for the dynamic import in Workbox is loading incorrectly

For my laravel/vuejs application, I am utilizing workbox and babel dynamic imports. Additionally, I am making use of the laravel-mix and laravel-mix-workbox plugin to compile and generate service worker via generateSW(). The assets load correctly on the r ...

"We are experiencing issues with the app.get function and it is

Although my backend is successfully serving other files, I have encountered an issue with loading new files that are located in a folder named js within the directory. These specific files are not being loaded, and despite spending an hour trying to troubl ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

Identify the activation of the "Inspect Element" feature

On Samy Kamkar's personal website at , there is a clever feature that detects when the console is opened and automatically clears the source code/console. It's a fascinating display of coding magic! https://i.stack.imgur.com/kag6U.jpg Curious t ...

Exploring the integration of datatables.net-vue3 with Vue.js 3 in Visual Studio: A step-by-step guide

I am trying to integrate datatables.net-vue3 with Vue.js 3 in Visual Studio. I have installed it using npm like so. However, I am facing issues with the imports in Visual Studio. I have tried importing them this way but it doesn't seem to work for me ...

Express middleware for serving static files using express.static() is not properly handling routing and is throwing an error stating that next()

During the development and testing phase on my local machine, everything was working as expected. However, once deployed to our UAT environment using Docker, I encountered some issues that are puzzling me: next() is not a function Another problem I'm ...