Tips for organizing my data upon its return into a more efficient structure

I need to restructure API data that is not optimized in its current format

Unfortunately, I am unable to ask backend developers to make the necessary changes, so I am exploring ways to clean up the model locally before using it in my Angular 2 application.

For instance, the data I receive is a flat object containing tables and user information

{$id: "400", sqlTable: "Customer", admin: 1, test: 3}

It is more efficient to filter this data and place users into a sub-object in order to speed up rendering without the need for conditional testing.

Desired structure:

"sqlTable":"value",
"Users":[
  "user1name":permission,
  "user2name":permission
]

From the original data:

  • $id is not essential (thus, it was removed)
  • sqlTable represents the table name
  • admin and test fields are considered as Users

Therefore, the "rule set" is that anything other than sqlTable is classified as a User and should be transferred to a Sub Object called Users.

I would greatly appreciate it if someone could provide an example in JS/TS on how to move the key/value data into the sub-structure based on these rules.

Here is the complete returned data:

{  
   "$id":"399",
   "IsFailure":false,
   "IsSuccess":true,
   "Value":[  
      {  
         "$id":"400",
         "sqlTable":"Customer",
         "admin":1,
         "test":null
      },
      {  
         "$id":"401",
         "sqlTable":"CustomerAddress",
         "admin":null,
         "test":null
      },
      {  
         "$id":"402",
         "sqlTable":"NewTable",
         "admin":null,
         "test":null
      }
   ]
}

Answer №1

To enhance the data presentation, I would first apply some transformations to the data. Here's an example of how I would approach it:

const data = {
  $id: "399",
  IsFailure: false,
  IsSuccess: true,
  Value: [
    {
      $id: "400",
      sqlTable: "Customer",
      admin: 1,
      test: null
    },
    {
      $id: "401",
      sqlTable: "CustomerAddress",
      admin: null,
      test: null
    },
    {
      $id: "402",
      sqlTable: "NewTable",
      admin: null,
      test: null
    }
  ]
};

// Perform mapping on each item in "Value"
let result = data.Value.map(table => {
  // Create a new object 'users' by spreading the original object
  let users = { ...table };
  // Remove unnecessary keys from 'users'
  delete users.sqlTable;
  delete users.$id;
  // Rearrange the object to fit the new structure
  return { sqlTable: table.sqlTable, Users: users };
});

console.log(result);

Answer №2

Your original inquiry sought an array of users, and your feedback highlighted the necessity of including a name and permissions key in the user object. By merging these requirements, you can achieve the desired transformation in a single statement as shown below:

const result = data.Value.map(value => ({
      table: value.sqlTable,
      users: Object.entries(value).filter(([key]) => key !== "$id" && key !== "sqlTable")
        .map(([key, value]) => ({
          name: key,
          permissions: value
        }))
    }))

const data = {
  $id: "399",
  IsFailure: false,
  IsSuccess: true,
  Value: [{
      $id: "400",
      sqlTable: "Customer",
      admin: 1,
      test: null
    },
    {
      $id: "401",
      sqlTable: "CustomerAddress",
      admin: null,
      test: null
    },
    {
      $id: "402",
      sqlTable: "NewTable",
      admin: null,
      test: null
    }
  ]
};


const result = data.Value.map(value => ({
  table: value.sqlTable,
  users: Object.entries(value).filter(([key]) => key !== "$id" && key !== "sqlTable")
    .map(([key, value]) => ({
      name: key,
      permissions: value
    }))
}))

console.log(result);

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

Explicit declaration of default parameters

Check out the helpful solution In regard to the following code snippet, type C = { a: string, b: number } function f({ a, b } = {a:"", b:0}): void { // ... } Can you explain the syntax for explicitly typing the default parameter? ...

Adjust the dimensions of a Three.js generated 3D cube dynamically during execution

Is it possible to dynamically change the dimensions (width/height/length) of a 3D Cube created with Three.js? For example, I found a Fiddle on Stack Overflow that changes the color of a Cube at runtime: http://jsfiddle.net/mpXrv/1/ Similarly, can we modi ...

Avoiding infinite loops in JavaScript events

This particular issue involves functions specific to D3, but is not limited to D3. I have developed two D3 charts and implemented zoom functionality on both with the intention of synchronizing the zoom scale and position - so that when one chart is zoomed, ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Establishing the maximum width of a Vuetify expansion panel component

https://i.sstatic.net/QqKVv.png I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansio ...

Tips for integrating Typescript definitions into the Express req and res objects

I have been encountering numerous errors in my REST API controller functions, specifically: error TS7006: Parameter 'req' implicitly has an 'any' type. The same issue is present for res. I have tried various solutions involving typing ...

What is the process by which JavaScript evaluates the closing parenthesis?

I'm currently working on a calculator project that involves evaluating expressions like (5+4). The approach I am taking is to pass the pressed buttons into an array and then create a parse tree based on the data in that array. One issue I'm faci ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

When refreshing the page, the authentication token set in the Vuex store using axios in Nuxt.js/Vue.js gets reset

Here is the code snippet I am using to manage login, logout, user retrieval, and token setting for all axios requests as an auth header. While this code works perfectly during client-side rendering - such as logging in, storing the token in cookies, etc. ...

NPM is lacking in providing sufficient guidance on resolving dependency problems

While attempting to incorporate Typescript into my Gatsby project after the fact, I encountered a cryptic error from NPM: npm ERR! code EOVERRIDE npm ERR! Override for @types/react@* conflicts with direct dependency npm ERR! A complete log of this run can ...

Problem with vueJS List Transition not being triggered

Within my Vue JS App, I encountered a situation where I have a list of items that change order randomly when the user clicks a button. Despite successfully using Vue.set to dynamically reposition the list elements, I faced an issue with adding a transition ...

Building TypeScript Model Classes

Greetings! As a newcomer to TypeScript with a background in both C# and JavaScript, I am on a quest to create class models resembling those found in C#. Here's my attempt so far: export class DonutChartModel { dimension: number; innerRadius: ...

Exploring the concept of self in JavaScript

Exploring the concept of "self" magic, take a peek at this excerpt from nodejs (which is not complete). Socket.prototype.connect = function(options, cb) { ...... var self = this; var pipe = !!options.path; if (this.destroyed || !this._handle) { ...

Identifying when an image element is within the viewport using jQuery Mobile

Looking for a solution to bypass the image size download limit on mobile devices by detecting when an image is in view and then downloading it. Also interested in replacing the image src with a smaller image to free up memory. Any tips on how to efficientl ...

What is the best way to open a browser window at a quarter of its default size?

Is there a way to open a window at 25% of its default device browser window size? I attempted the code below, which worked. However, it only accepts pixel inputs and not relative % values. This makes it non-scalable across various devices. window.resizeT ...

Ensuring User Input Integrity with JavaScript Prompt Validation

I need help with validating input from a Javascript prompt() in an external js file using HTML code. I know how to call the Javascript function and write the validation logic, but I'm unsure how to handle the prompt and user input in HTML. Do I need ...

How can I create a clickable <div> element containing multiple links and trigger only one action?

Within my code, there is a <div> element that has been made clickable. Upon clicking this <div>, the height and text expand using the jQuery function $(div).animate();. While this functionality works as intended, I am encountering a slight issu ...

Uploading photos to Postgres through express/multer

Currently, I am using Postman to send images to a POST route through the Express library. However, when I retrieve the buffer of binary data, I am unable to process it accordingly. Will using body-parser resolve this issue? This is how I am uploading the ...

What types should you use for an Axios response in React and TypeScript?

Trying to display a basic user list fetched from an API, which returns the following data: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] Struggling to understand how to deal ...