基于属性数组选择对象属性的地图功能

发布于 2025-01-20 03:28:31 字数 1140 浏览 2 评论 0原文

我想找到一个解决方案,允许我使用映射函数基于属性数组提取属性。理想情况下,我想要一个通用的解决方案,这样我就不必为每个变体对地图函数进行硬编码。

我的用例:我正在构建一个管理仪表板,需要显示 20 多个表 - 每个表都有不同的列组合。使用 VueJS 我有一个表格组件来渲染表格,但目前每个表格都显示完全相同的列。

// every table shows these 4 columns
this.rows = this.menu.MenuItem.map(r => ({
   Id: r.Id,
   Name: r.Name,
   Description: r.Description,
   Category: r.Category
}))

我希望每个表都能够定义它想要显示的列,而不是每个表都使用相同的列。每个表都使用相同的表组件,因此我需要一个通用的解决方案来避免编写大量的 if-else 块。

const MenuColumnMapping = [
    { menu: "Menu 1", columns: ["Id", "Name", "Description"] },
    { menu: "Menu 2", columns: ["Id", "Name", "Description", "Category" ] },
    { menu: "Menu 3", columns: ["Id", "Name", "Description", "Price", "Condition" ] },
    ...
]

如何重写 map 函数以根据给定菜单的 columns 数组选择属性?

let cols = MenuColumnMapping
              .filter((m) => m.menu === this.menu.Name)
              .map((m) => m.columns)

// ex. cols = [ "Id", "Name", "Description", "Category" ]
this.rows = this.menu.MenuItem.map(r => ({
   
   // How can I select only the properties listed in cols

}))

I would like to find a solution that would allow me to use the map function to extract properties based on an array of properties. Ideally I would like a general solution so that I do not have to hard code the map function for each variation.

My use case: I am building an admin dashboard that will need to display 20+ tables - each with a different combination of columns. Using VueJS I have a table component to render the table but currently each table has the exact same columns being shown.

// every table shows these 4 columns
this.rows = this.menu.MenuItem.map(r => ({
   Id: r.Id,
   Name: r.Name,
   Description: r.Description,
   Category: r.Category
}))

Instead of the same columns for each table, I would like each table to be able to define which columns it would like to display. The same table component is used for each table, so I need a general solution to avoid writing a massive if-else block.

const MenuColumnMapping = [
    { menu: "Menu 1", columns: ["Id", "Name", "Description"] },
    { menu: "Menu 2", columns: ["Id", "Name", "Description", "Category" ] },
    { menu: "Menu 3", columns: ["Id", "Name", "Description", "Price", "Condition" ] },
    ...
]

How could I rewrite the map function to select the properties based on the array of columns for a given menu?

let cols = MenuColumnMapping
              .filter((m) => m.menu === this.menu.Name)
              .map((m) => m.columns)

// ex. cols = [ "Id", "Name", "Description", "Category" ]
this.rows = this.menu.MenuItem.map(r => ({
   
   // How can I select only the properties listed in cols

}))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文