基于属性数组选择对象属性的地图功能
我想找到一个解决方案,允许我使用映射函数基于属性数组提取属性。理想情况下,我想要一个通用的解决方案,这样我就不必为每个变体对地图函数进行硬编码。
我的用例:我正在构建一个管理仪表板,需要显示 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论