gpt4 book ai didi

javascript - 获取对象数组中的特定元素

转载 作者:行者123 更新时间:2023-12-02 23:24:33 25 4
gpt4 key购买 nike

我正在尝试使用对象 props 数组中的部分(而非全部)数据来设置表数据。

我从我的操作中设置了一个对象数组:

export const getTenants = ({ userID }) => {
return (dispatch) => {
const test = [
{ id: 1, fullName: 'Tenant 1', unitName: '101', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 2, fullName: 'Tenant 2', unitName: '102', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 3, fullName: 'Tenant 3', unitName: '103', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 4, fullName: 'Tenant 4', unitName: '104', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 5, fullName: 'Tenant 5', unitName: '105', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 6, fullName: 'Tenant 6', unitName: '106', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 7, fullName: 'Tenant 7', unitName: '107', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
{ id: 8, fullName: 'Tenant 8', unitName: '108', leaseEndDate: '01/01/2020', tenantEmail: 'none@none.com' },
];
dispatch({
type: GET_TENANT_DATA,
payload: test
});
};
};

然后,在我的页面中,我想仅按单位、租赁结束日期、姓名和电子邮件的顺序设置 tableData。

this.state = {
tableHead: ['Unit', 'Lease End Date', 'Tenant', 'Tenant Email'],
tableData: this.props.data
};

有办法吗?谢谢

最佳答案

设置 header => 对象键映射并循环遍历 tableHead 以提取所需的数据。

this.headerMap = {
'ID': 'id',
'Tenant': 'fullName',
'Unit': 'unitName',
'Lease End Date': 'leaseEndDate',
'Tenant Email': 'tenantEmail',
}

this.state = {
tableHead = ['Unit', 'Lease End Date', 'Tenant', 'Tenant Email'],
tableData: this.props.data.map(row => tableHead.map(header => row[this.headerMap[header]]))
}

这将创建一个数组数组:

[
['101', '01/01/2020', 'Tenant 1', 'none@none.com'],
['102', '01/01/2020', 'Tenant 2', 'none@none.com'],
['103', '01/01/2020', 'Tenant 3', 'none@none.com'],
['104', '01/01/2020', 'Tenant 4', 'none@none.com'],
['105', '01/01/2020', 'Tenant 5', 'none@none.com'],
['106', '01/01/2020', 'Tenant 6', 'none@none.com'],
['107', '01/01/2020', 'Tenant 7', 'none@none.com'],
['108', '01/01/2020', 'Tenant 8', 'none@none.com']
]

关于javascript - 获取对象数组中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56795074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com