Tips for organizing an object according to specific attributes

Within my table, I have implemented a feature that allows the display of only selected columns at a time.

To achieve this, I store the chosen columns (table headings) in an array called selectedTableHeaders.

The next step is to filter out a new array based on the properties listed in the selectedTableHeaders, ensuring that only the selected columns are displayed in the table data.

In addition, it's crucial to maintain the correct order of the tableData. For example, if a user disables table header 3, then table header 6, and later enables 3 again, 3 should be added back in its original position. This means reordering the tableData according to the table headers as well.

What would be the best solution for achieving this?

const selectedTableHeaders = [
    "table_header_1",
    "table_header_3",
    "table_header_5",
    "table_header_6"
]

tableData [
    {
        "rowData": {
            "table_header_1": "0",
            "table_header_2": "data 2",
            "table_header_3": "US",
            "table_header_4": "data 4",
            "table_header_5": "-",
            "table_header_6": "data 6"
        }
    },
    {
        "rowData": {
            "table_header_1": "0",
            "table_header_2": "test 2",
            "table_header_3": "GB",
            "table_header_4": "test 4",
            "table_header_5": "Y",
            "table_header_6": "test data 6"
        }
    },
    {
        "rowData": {
            "table_header_1": "0",
            "table_header_2": "test 2",
            "table_header_3": "DE",
            "table_header_4": 70000118,
            "table_header_5": "-",
            "table_header_6": "test table 6"
        }
    }
]

I attempted to tackle this issue with the following approach:

this.tableData.forEach((tableItem) => {
        const newArray = Object.assign(...selectedTableHeaders.map(k => ({ [k]: tableItem[k] })));
})

However, I am not getting the values in the newArray as expected. Is there a more effective way to handle this process and also retrieve the property values in the new array?

The goal is to generate a new array containing only the selected columns and ensure the correct ordering of the table data based on the table headings.

For instance:

If the heading order is:

"table_header_2",
"table_header_1",
"table_header_5",
"table_header_4"

The corresponding rowData should look like this:

"rowData": {
    "table_header_2": "data 2 ",
    "table_header_1": "0",
    "table_header_5": "-",
    "table_header_4": "data 4",
}

Answer №1

If your fields are already in the desired order, you can simply map them and access the values using keys.

reg.

const selectedTableHeaders = [
  "table_header_1",
  "table_header_3",
  "table_header_5",
  "table_header_6",
];

const tableData = [
  {
    rowData: {
      table_header_1: "0",
      table_header_2: "data 2 ",
      table_header_3: "US",
      table_header_4: "data 4",
      table_header_5: "-",
      table_header_6: "data 6",
    },
  },
  {
    rowData: {
      table_header_1: "0",
      table_header_2: "test 2",
      table_header_3: "GB",
      table_header_4: "test 4",
      table_header_5: "Y",
      table_header_6: "test data 6",
    },
  },
  {
    rowData: {
      table_header_1: "0",
      table_header_2: "test 2",
      table_header_3: "DE",
      table_header_4: 70000118,
      table_header_5: "-",
      table_header_6: "test table 6",
    },
  },
];

function filter(src, fields) {
  return src.map((row) => ({
    rowData: Object.fromEntries(
      fields.map((m) => [m, row.rowData[m]])),
  }));
}

console.log(filter(tableData, selectedTableHeaders));

Answer №2

To achieve this task, simply iterate through the array object.

See it in action:

const desiredTableHeaders = [
    "table_header_1",
    "table_header_3",
    "table_header_5",
    "table_header_6"
]

const dataForTable = [
    {
        "rowData": {
            "table_header_1": "0",
            "table_header_2": "data 2 ",
            "table_header_3": "US",
            "table_header_4": "data 4",
            "table_header_5": "-",
            "table_header_6": "data 6"
        }
    }, {
        "rowData": {
            "table_header_1": "0",
            "table_header_2": "test 2",
            "table_header_3": "GB",
            "table_header_4": "test 4",
            "table_header_5": "Y",
            "table_header_6": "test data 6"
        }
    }, {
        "rowData": {
            "table_header_1": "0",
            "table_header_2": "test 2",
            "table_header_3": "DE",
            "table_header_4": 70000118,
            "table_header_5": "-",
            "table_header_6": "test table 6"
        }
    }
];

const result = dataForTable.map((rowDataObject) => {
    Object.keys(rowDataObject.rowData).forEach((headerKey) => {
    if (!desiredTableHeaders.includes(headerKey)) {
      delete rowDataObject.rowData[headerKey]
    }
  });
  return rowDataObject.rowData;
});

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

Detecting changes in checkbox states

In my current scenario, I have a section of the screen that can be shown or hidden depending on whether a checkbox is checked. The user can change the state of the checkbox manually or programmatically. The challenge lies in detecting this change and upda ...

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

An error occurs when trying to modify the classList, resulting in an Uncaught TypeError for setting an indexed property

I am attempting to modify the classes of multiple sibling elements when a click event occurs. Some of these elements may have multiple classes, but I always want to change the first class. Below is the code that I created: let classList = event.currentTa ...

The absence of the object's shadow is conspicuously noticeable - three.js

View Screenshot Hey there! I recently exported a 3D model tree from Blender and everything seemed to have gone smoothly, but I encountered an issue. The shadow appears on the trunk and branches, however, it is not reflecting properly. Could this be due to ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Guide to modifying the class color using javascript

I am experiencing an issue with this particular code. I have successfully used getElementById, but when I try to use document.getElementsByClassName("hearts");, it does not work as expected. This is a snippet of my HTML code: status = 1; function change ...

The operation could not be completed with exit code 1: executing next build on Netlify platform

Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

Pattern matching algorithm designed to eliminate background-color attributes

Looking to strip out any "background-color:[whatever];" styles from the text within a div. The plan is to eliminate all inline background-color styles completely. I've been eyeing JavaScript's string.replace(regex,str) as a potential solution ...

Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns: * Column Letters: ['a', 'b', 'c', 'd', etc.] * ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Encountering a 401 Error while trying to host an Angular app on Google Cloud Storage

I am currently facing an issue with deploying my Angular app to a Google Cloud Storage bucket. The bucket is public and set up to be served as a custom website via CNAME (test.example.com). The main page and 404 handler are mapped to index.html, but I am e ...

Enhanced Stay Connected feature for inclusions and exclusions

I am facing an issue with excluding multiple components from my KeepAlive component. Despite trying to exclude more than one component, it seems to only work for a single component. <KeepAlive exclude="DetailView, NewClaim"> <router- ...

Guide on how to retrieve a single document (mongoose/mongoDB)

Storing data in a database is crucial for many applications. { "_id": "62fa5aa25778ec97bc6ee231", "user": "62f0eb5ebebd0f236abcaf9d", "name": "Marketing Plan", "columns": [ { ...

Jade, res.render, and res.write are essential tools for rendering

I am currently working on creating a simple FTP client in Node.js. Everything seems to be running smoothly, but I am facing difficulty in displaying the "singleFile.name" in my Jade template. app.post('/ftp/login', function(req, res){ ftp.ls(" ...

Can PHP's CURL handle cookies?

Recently, I set up a poll using PHP that allows voting without the need for an account. However, I became concerned about the possibility of the poll being vulnerable to hacking and spam votes. I discovered that I could potentially vote multiple times by ...

How to capture a specific part of a model using Autodesk Forge Viewer

I have a situation where I have 20 element Ids that I need to capture screenshots of in a specific size (400x400) like a detail view. The current viewer I am using has different dimensions, so I'm wondering if there is a way to achieve this and return ...

Connect button with entry field

I want to create a connection between an input element and a button, where the button triggers the input and the input remains hidden. Here is a solution that I came across: <a href="javascript:void(0)" id="files" href=""> <button id="uploadDe ...

Begin the animation again by hitting the start button, using the burst-engine and canvas

I have successfully created a simple animation using Burst Engine and HTML5. My goal is to make the start button trigger the animation to restart if pressed twice. Currently, when I press it, the animation just starts and nothing else happens. I suspect t ...