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

Ways to switch out the background image using jQuery

I am currently using jQuery to dynamically change the background image of a web page. Right now, I have implemented two separate buttons that toggle between Image A and Image B. By default, Image A is displayed on the page. My goal is to enhance this func ...

Acquiring mapping information through JSON data retrieval

Overview : Each levelNum has three corresponding dropdowns. For example, the dropdown for levelNum2 includes (Department-Unit-1, Department-Unit-2 & Department-Unit-3), levelNum3 includes (Division-Unit-1 & Division-Unit-2), and levelNum4 includes ...

Guide to developing a custom plugin for Nuxt.js

This is the content of my rpc.js plugin file: const { createBitcoinRpc } = require('@carnesen/bitcoin-rpc') const protocol = 'http' const rpcuser = 'root' const rpcpassword = 'toor' const host = '127.0.0.1&apo ...

How to retrieve the initial element of a specific tag using jQuery

As I am transitioning from standard JavaScript to jQuery in order to achieve cross browser compatibility, I am seeking guidance on how to rewrite certain functions in jQuery. Specifically, I am looking for the correct way to find the first element using jQ ...

Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems. The console log appears as follows ...

Error message: Unable to access properties of null when calling 'registerPlugin' in @devexpress/dx-react-grid-material-ui

I have developed a CustomGrid component that is based on the DevExpress Grid component. So far, it has been working smoothly. Here's how the implementation looks like in App.tsx: import Paper from "@mui/material/Paper"; import { Table, TableHeaderRow ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

Troubleshooting Problems with Loading Data into Highcharts using Javascript

The server is returning data in the following format: {"barData": [ {"Accepted":[0,0,0]}, {"Rejected":[0,0,0]}, {"In_Process":[0,1,0]}] } On the browser, it appears as follows: I initially thought that this was the correct st ...

Issue with Bootstrap alignment on the right side

Just finished creating my 'navbar' in bootstrap, but I'm having trouble aligning my unordered list to the right. It's staying in the middle no matter what I try. Can someone please help? Feeling really confused... HTML: <div class= ...

Problem with selecting and deselecting bus seat reservations accurately

I'm currently developing a bus booking application. To create the seat booking layout, I used Recyclerview and GridLayoutManager. The layout was created successfully with 4 seats in each row and 5 seats in the last row, resulting in a GridLayoutManage ...

Save a canvas image directly to your WordPress media library or server

I'm working on integrating a feature that enables users to save a png created on a canvas element into the WordPress media library, or at least onto the server (which is an initial step before sharing the image on Facebook, as it requires a valid imag ...

The process of mounting a Vue component involves removing the surrounding div element

I am facing an issue while mounting a component on a function. Everything seems to be working fine initially. However, I have configured it to destroy the div after a certain number of seconds. The problem arises when I attempt to add the component again; ...

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

What steps should be taken to fix the error "Warning: Encountered multiple children with the same key" in React.js?

I'm having trouble fetching and displaying data from an API. Whenever I attempt to show the data, I encounter the following error message: Alert: Found two children using the same key, [object Object]. Keys must be unique so that components can pro ...

Creating a dynamic form in Django that allows users to input text and insert images using AJAX technology

My goal is to develop a website for creating articles that go beyond the standard models.TextField setup commonly used with Django. I want users to have the ability to add an arbitrary number of text and image fields to their articles, while also ensuring ...

Locate the point at which the two strings no longer match in their indices

Consider having 2 strings: var a = "abcdef", b = "abcdefgh"; I am searching for the first index where the complete match is broken without needing to iterate over both strings and compare each character with a loop. In this instance, I need to identify ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

What could be causing my component to not refresh when used as a child?

I have been experimenting with some code to track rerenders. The initial approach failed when passing <MyComponent> as a child component. it("should return the same object after parent component rerenders", async () => { jest.useF ...

The integration between React hook form and reactstrap input components is not functioning properly

Having an issue with react-hook-form and reactstrap. The component List.jsx is causing trouble: import { useContext, useEffect } from "react"; import { ListContext, ADD_LIST } from '../providers/ShoppingListProvider'; import { Link } from "react- ...