Narrow down an array of objects by matching a specific property and value to a separate array of objects

I am facing a challenge with two sets of arrays - one for the headers (columns) of a table and the other for the rows.

const headers = [
  {
    text: 'Dessert (100g serving)',
    align: 'left',
    sortable: false,
    value: 'name',
    visible: true
  },
  { text: 'Calories', value: 'calories', visible: true },
  { text: 'Fat (g)', value: 'fat', visible: true },
  { text: 'Carbs (g)', value: 'carbs', visible: true },
  { text: 'Protein (g)', value: 'protein', visible: true },
  { text: 'Iron (%)', value: 'iron', visible: true }
]

const desserts = [
  {
    name: 'Frozen Yogurt',
    calories: 159,
    fat: 6.0,
    carbs: 24,
    protein: 4.0,
    iron: '1%'
  },
  {
    name: 'Ice cream sandwich',
    calories: 237,
    fat: 9.0,
    carbs: 37,
    protein: 4.3,
    iron: '1%'
  },
  {
    name: 'Eclair',
    calories: 262,
    fat: 16.0,
    carbs: 23,
    protein: 6.0,
    iron: '7%'
  },
  {
    name: 'Cupcake',
    calories: 305,
    fat: 3.7,
    carbs: 67,
    protein: 4.3,
    iron: '8%'
  }
]

My goal is to allow users to choose which columns they want to view in the table by using checkboxes.

Using Vue.js, I have created a collection of checkboxes that are bound to headers from the headers array as follows:

computed: {
  filteredHeaders () {
    return this.headers.filter(header => header.visible)
  }
}

This functionality works well, where the table column headers change based on selected checkboxes.

However, I am struggling to filter the row data (desserts) based on the selected columns (filteredHeaders).

I attempted the following approach:

computed: {
  ...
  filteredItems () {
    return this.desserts.filter(dessert => {
      return this.filteredHeaders.some(header => {
        return Object.keys(header).some(prop => {
          return dessert[prop] != header[prop] && header.visible
        })
      })
    })
  }
}

Despite not encountering any errors, the result of filteredItems remains unchanged from the original desserts, and properties that should be excluded still appear when visible is set to false through checkboxes.

I believe I'm close to solving this issue, but I haven't quite hit the mark yet!

Answer №1

To achieve the desired outcome, consider using this approach:

const categories = [{
    type: "Fruit",
    color: "yellow",
    shape: "round",
  },
  {
    type: "Vegetable",
    color: "green",
    shape: "long",
  },
  {
    type: "Dairy",
    color: "white",
    shape: "square",
  }
];

const items = [{
    name: "Banana",
    category: "Fruit",
    cost: 0.50,
  },
  {
    name: "Broccoli",
    category: "Vegetable",
    cost: 1.00,
  },
  {
    name: "Milk",
    category: "Dairy",
    cost: 2.50,
  }
];

const filterItems = (items, categories) => {
  return items.map(item => {
    const filteredItem = {};
    categories.forEach(category => {
      if (item.category === category.type) {
        filteredItem["name"] = item.name;
        filteredItem["cost"] = item.cost;
      }
    });
    return filteredItem;
  });
};

console.log(filterItems(items, categories));
console.log(filterItems(items, [{
  type: "Dairy",
  color: "white",
  shape: "square",
}]));

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

Determine the coordinates of the mouse cursor within a specific div element

Similar Questions: Determining Mouse Position Relative to a Div Getting the Mouse Position Using JavaScript in Canvas Is there a way to retrieve the mouse position within a canvas element with fixed dimensions and automatic margin? I am unable to ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Is AngularJS the right choice for developing this application?

Recently, I've come to the realization that I want to dive into the world of AngularJS framework after working with jQuery for several years. I have a vision of developing an application that allows users to easily modify webpage DOM using a browser- ...

The issue of Next.js redux useSelector causing HTML inconsistency

Currently, I am utilizing Next.js for the development of a React application. In order to manage the state, I have integrated redux along with redux-toolkit. A peculiar error has surfaced in the console with the message: Warning: Did not expect server H ...

I encountered an issue with the mui TextField component in React where it would lose focus every time I typed a single character, after adding key props to

I'm encountering an issue with a dynamic component that includes a TextField. Whenever I add the key props to the parent div, the TextField loses focus after typing just one character. However, when I remove the key props, everything works as expected ...

Trigger event once item is selected from the jQuery combobox dropdown

I have implemented a custom autocomplete combobox using the jQuery UI library to create text fields with dropdown functionality. This hybrid input allows users to either select an item from the dropdown or enter free text manually. However, I need to trigg ...

The created hook is not pausing for the resolution of the beforeEach action promise

My router has a beforeEach route guard that triggers the fetchWorkspaces action. This action uses Axios to make a request, and then updates the state with the response data. However, when I try to access the state in the created hook of the component and ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

Transferring files and folders to the Electron Distribution directory

In short: I'm looking for a way to automate the process of copying files/directories from my src folder to dist/resources when packaging using Electron-packager. This need arose because I have JSON files in folders that need to be transferred to a sp ...

Include CLI input into JavaScript variable within the Webpack build process

I am currently attempting to incorporate a variable into my app.js file during the build process. For instance: //app.js var myvar = {{set_from_cli}}; Afterwards, I would like to execute something such as webpack -p --myvar='abc' which would pr ...

Modal does not close

I am experiencing an issue with closing a modal. I have checked jQuery and everything seems to be working fine. Currently, I am using version 1.12.4 and have the following script tag in the head of my code: <script src="https://ajax.googleapis.com/aja ...

React JS - Building a dynamic multi-tiered dropdown navigation system

Link to view the illustrative example: here. Could anyone advise on a solution for ensuring only one submenu is open at a time? For instance, when "menu 3" is opened, I would like "menu 2" to be automatically closed. ...

Angular JS causing text alignment issues in table cells when viewed on mobile devices

I have created a web application that requires both desktop and mobile views, utilizing Angular JS. Everything is functioning as expected except for the text alignment within tables. I attempted using <td align="left">, but it did not produce any cha ...

Step-by-step guide for launching a Laravel 5 & Vue.js project

My local server hosts a Laravel 5 & Vue.js application (Vue.js comes integrated with Laravel). I am looking to deploy this application on a real server like "000webhost.com" for testing purposes. While Laravel functions properly after deployment, Vue.js do ...

Displaying a single result in Angular from JSON without using the ng-repeat filter

Currently, I am working on developing an app to display news updates from a JSON API. The issue I am facing is that loading all the data from the JSON and filtering it using ng-repeat is causing slow performance, as there is a large amount of data. I woul ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

The Javascript function will keep on executing long after it has been invoked

I am currently facing an issue with calling a JavaScript function within an AJAX call. The progress function below is supposed to be executed every time the for loop runs. However, the problem is that although progress is being run as many times as the for ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

"Utilizing the Datatable feature in Vuetify for selecting multiple rows with the Shift+Click

I'm currently using Datatable by Vuetify version 1.5.x I have set up the checkboxes to allow for multiple row selections, and I'd like to implement a Shift + Click functionality similar to how it works in Gmail, so users can select multiple rows ...