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

Maintaining the sequence of a PHP associative array when transferring it to JavaScript via ajax

Below is the code from my PHP file: GetUserArray.php $Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia'); echo json_encode($Users); Here is the AJAX request I am using: $.ajax({ ...

How to troubleshoot the Uncaught TypeError in Vue.js: data.filter is not recognized as a function in my code

My JSON structure looks like this: items: {"countcats":2,"countsubcats":7, "catsubcatsdata":{ "15978738e6cd1e":{"title":"Test 1","description":"blablabla", "subcats":{ "1597873b16 ...

Having issues with AngularJS where ng-table/ng-repeat rows are failing to load properly

I've been following a tutorial on using ng-Table, which can be found Here. When I download the example from Git, it loads without any issues. However, when I try to replicate even the simplest example myself, the column headers and filters load but th ...

How can I pass function arguments dynamically to a nested function in Node.js?

Currently using Node 6.11.0, I am attempting to accomplish the following dynamically: const parentFunc = (arg1, arg2, arg3, arg4) => { childFunc('foo', arg1, arg2, arg3, arg4); }; I have attempted this method (without success): const pare ...

What is the best way to implement page navigation within Nuxt?

Is there a way to efficiently paginate and display comments from this particular API? Should we retrieve the entire object and use slice() for pagination, or is there a specific method for fetching comments in chunks for a single page? Furthermore, how c ...

Is there a lack of mutation occurring in the custom component?

Here is my current structure: CHILD COMPONENT // HTML <v-select v-bind:items="selectItems" v-model="selectedItemModel" label="Category" item-value="text" ></v-select> <v-text-field label="Enter Value" type="number" v-model="compValM ...

How can I unselect a radio button by double clicking on it?

I am in need of a specific feature: When a user clicks on a radio button that is already checked, I want it to become unchecked. I've attempted to implement this code but unfortunately, it has not been successful. $(document).on('mouseup' ...

Struggling to update the previousCode state with the useState hook in React

I'm having trouble understanding why the state isn't changing when using setPreviousCode in React and JavaScript. I'm trying to store the previously scanned text in the variable previousCode. import React, { useEffect, useState } from " ...

connect the input to a factor using v-model

I currently have a value that I need the user to adjust. Here's my current setup: <input type="number" v-model="value" step="any"/> However, the internal value is in radians while I want the user to see and input a degree value. So, I want th ...

Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page. As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen. ...

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

Extracting precise information from a JSON file using Angular's $http.get

I am struggling with extracting a specific user from a JSON file containing a user list and displaying it on an Angular index page. Despite extensive research, I have been unable to find a satisfactory solution. The user list must remain in a JSON file ins ...

Issue encountered while attempting to deactivate button until numerical data is entered in the OTP field using Vuejs

otp_value: '', isFadeout: false, verifyOtp() { this.disabled = true; this.otpBtnClicked = false; this.verified = true; }, <input class="o ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

When should separate controllers be created for a list of values in a Laravel REST API?

Imagine I have a straightforward API for user registration. This API collects basic information like Name, email, state, gender, and marital status for each user. I already have database tables pre-populated with ids for state, gender, and marital status o ...

How can we make it simple for users to update webpage content using a file from their computer?

I am developing a custom application specifically for use on Firefox 3.6.3 in our internal network. My goal is to dynamically update the content of the page based on a file stored locally on my computer. What would be the most straightforward approach to ...

Is there a way to retrieve the Boolean value from an ng-show attribute without having to re-evaluate the expression?

I'm currently working on a project that involves displaying and hiding a lot of content dynamically using ng-show. Some of the expressions being evaluated are quite lengthy, like this... <div ng-show="some.object.with.nested.values && ...

The JSON file containing API data is stored within the _next folder, making it easily accessible to anyone without the need for security measures or a login in the Next

When accessing the protected user Listing page, we utilize SSR to call the api and retrieve all user records which are then rendered. However, if one were to check the Network tab in Chrome or Firefox, a JSON file containing all user data is generated and ...