Proper method for retrieving and displaying information from a targeted JSON through an API

Utilizing a third-party API requires specifying the desired fields in the request. For instance:

axios.get("APIURL", {
    params: {
      fields: ["username", "phone", ...etc]
    }
  })

The response is typically structured like this:

{
    "data": [{
        "username": {
            "id": 17,
            "data": "JohnDoe",
            "created_at": "2019-05-09 15:52:23"
         }
    },
    {
         "phone": {
             "id": 2,
             "data": "+123456789",
             "created_at": "2019-05-08 17:31:52"
         }
    }]
}

To format the data for a vuetify table, it is necessary to create an object with the desired values:

response => {
      this.userInfo = {
        username: response.data.data[0].username.data,
        phone: response.data.data[1].phone.data
      };
    }

However, the current display of the data may not be ideal. As such, there are two key questions:

1) How can the data be extracted from the JSON to display in the vuetify table with username, phone, email, address, and other fields?

2) How should cases be handled when certain fields are undefined, leading to potential errors like "TypeError: Cannot read property 'data' of undefined"?

Your assistance is greatly appreciated!

Answer №1

To extract the necessary data from the response, you can utilize this custom function:

function extractData(data) {
  const extractedData = {};

  data.forEach((item) => {
    Object.keys(item).forEach((key) => {
      extractedData[key] = item[key].data;
    });
  });

  return extractedData;
}
this.userData = extractData(response.data.data) //example of function usage

Answer №2

Another approach could involve simplifying the object while parsing and then condensing the resulting array into an object:

var jsonData = '{"data":[{"username":{"id":17,"data":"JohnDoe","created_at":"2019-05-09 15:52:23"}},{"phone":{"id":2,"data":"+123456789","created_at":"2019-05-08 17:31:52"}}]}';

var parsedArray = JSON.parse(jsonData, (key, value) => value.data || value);

var simplifiedObj = parsedArray.reduce((accumulator, currentValue) => Object.assign(accumulator, currentValue), {});

console.log(simplifiedObj);
console.log(parsedArray);

Alternatively, without using reduce:

var simplifiedObj = {};
var jsonData = '{"data":[{"username":{"id":17,"data":"JohnDoe","created_at":"2019-05-09 15:52:23"}},{"phone":{"id":2,"data":"+123456789","created_at":"2019-05-08 17:31:52"}}]}';

JSON.parse(jsonData, (key, value) => value.data && key ? (simplifiedObj[key] = value.data) : value);

console.log(simplifiedObj);

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

sort by the last element in the array

I have implemented an angular table that is organized by an array. The structure is such that the second level depends on the first level, and the third level depends on the second, and so forth. For instance: A is the parent of B, B is the parent of C. ...

Change the value PRIOR to executing a function with ajax included

When the page loads, the following code triggers an API request and returns the result. Afterwards, there is code that updates one of the variables when a selector is changed, and then makes the API request again using the newsFeed() function. However, I& ...

The error message 'ReferenceError client is not defined' is indicating that the

I'm currently attempting to retrieve the id of clients connecting to my socket.io/node.js server by following the method outlined in the top response on how to get session id of socket.io client in Client. However, I am encountering an error message: ...

Discovering the specific value from a fixture file in Cypress

When I receive a JSON Response, how can I extract the "id" value based on a Username search? For instance, how can I retrieve the response with an "id" value of 1 when searching for the name "Leanne Graham"? It is important to note that the response valu ...

@vue/cli for automated unit testing

I'm currently using @vue/cli version 4.5.15 and looking to write tests for my components. However, when I run the command, yarn test:unit I encounter an error that says: ERROR command "test:unit" does not exist. Do I need to perform additional se ...

jquery kwicks problem

I have been grappling with a coding problem for hours on end and I have hit a wall. Assistance is needed. On a staging page, the code was tested and found to be functioning properly. However, on the live page, the same code fails to respond as expected. I ...

Verify the occurrence of a search result and if it appears more than once, only show it once using JavaScript

Hello all. Currently, I am developing an online users script using NodeJS and SocketIO. The functionality works fine, however, I am encountering an issue where if a user connects from multiple browsers, windows, or devices, it displays duplicate results li ...

Setting up the CSS loader in a Vue.js project using webpack

I am currently working on a new vue-cli project and have successfully installed the Pure.CSS framework using npm install purecss --save. However, I am struggling to seamlessly integrate, import, or load the css framework into my project. I am unsure of whe ...

Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail( ...

Navigating through an array of objects with Node.js

Recently, I integrated the ChartJS library into my Node web app to visualize data. The following is nested in a script tag on an EJS template page: <script> let playerStatChart = new Chart(myChart, { type: 'bar', data: { la ...

What mistakes am I making in this PHP code as I try to work with the select option?

Currently, I am developing a form that involves selecting values. If the user chooses 'yes', I want to display a text box section. However, the code below is not functioning as expected. <select id="gap" name="gap" onclick="gap_textbox();"> ...

Navigating Angular with relative paths: A guide to locating resources

Here is the structure of my app: index.html main.ts app |--main.component.html |--main.component.ts |--app.module.ts |--note.png ... etc I am trying to include the note.png file in main.component.html which is located in the same folder. I have att ...

If the value is null, pass it as is; if it is not null, convert it to a date using the

I am currently facing an issue regarding passing a date value into the rrule plugin of a fullCalendar. Here is the snippet of code in question: Endate = null; rrule: { freq: "Daily", interval: 1, dtstart: StartDate.toDate ...

Swap out .h and .m files within an iOS project's bundle directory in real-time

I am currently using the calculation.h and calculation.m files for some calculations in my project. These calculations may need to be modified while the application is live on the store. Therefore, I can only make changes to these calculations and update t ...

Guide on how to transmit an error message from PHP when handling a jQuery Ajax post request

Greetings! This is my inaugural inquiry, so please understand if I am a bit apprehensive. I am facing an issue in the following scenario... I have an Ajax request structured like this: $.ajax({ url: "test.php", method: "POST", data: { ...

Understanding how to display a component within another component in Vue.js

I am faced with a scenario where I have a component that has the following template: <div v-for:"item in store" v-bind:key="item.type"> <a>{{item.type}}</a> </div> Additionally, I have another component named 'StoreCompone ...

What is the best way to navigate to a specific location on a web page?

After clicking the "Add comment" link, a comment form popped up using Ajax. I now need assistance with scrolling to it, can you please help me out? ...

Troubleshooting: Why isn't my Vuetify v-form sending data when submitted

Apologies for any translation errors :) I have created a simple form to test retrieving data from my API using Vuetify. However, when I submit the form, the data from v-select is not being sent and I cannot figure out why. Typically, examples of these for ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

The attempt to run 'setProperty' on 'CSSStyleDeclaration' was unsuccessful as these styles are precalculated, rendering the 'opacity' property unchangeable

I am attempting to change the value of a property in my pseudo element CSS class using a JavaScript file. Unfortunately, I keep encountering the error mentioned in the title. Is there any other method that can be used to achieve this? CSS Code: .list { ...