函数参数作为映射值

function argument as map value

美好的一天,我有一个对象数组,我正在尝试映射条目。

const monthOnject = {
    "March 2022": [
        {
            "date": "2022-03-16",
            "amount": "-50",
            "description": "mar ",
            "category": "Salary",
            "createdAt": "2022-04-15T06:27:16.953Z",
            "updatedAt": "2022-04-15T06:27:16.953Z",
            "__v": 0
        }
    ],
    "April 2022": [
        {
            "date": "2022-04-15",
            "amount": "100",
            "description": "apr",
            "category": "Debt",
            "createdAt": "2022-04-15T06:27:02.381Z",
            "updatedAt": "2022-04-15T06:27:02.381Z",
            "__v": 0
        },
        {
            "date": "2022-04-19",
            "amount": "-150",
            "description": "apr",
            "category": "Salary",
            "createdAt": "2022-04-15T06:27:33.035Z",
            "updatedAt": "2022-04-16T11:48:39.540Z",
            "__v": 0
        },
        {
            "date": "2022-04-26",
            "amount": "11",
            "description": "asd",
            "category": "Credit",
            "createdAt": "2022-04-15T18:03:24.785Z",
            "updatedAt": "2022-04-16T11:51:49.503Z",
            "__v": 0
        },
        {
            "date": "2022-04-27",
            "amount": "111",
            "description": "asdad",
            "category": "Debt",
            "createdAt": "2022-04-19T13:59:30.821Z",
            "updatedAt": "2022-04-19T13:59:30.821Z",
            "__v": 0
        }
    ],
    "May 2022": [
        {
            "date": "2022-05-18",
            "amount": "-200",
            "description": "may",
            "category": "Salary",
            "createdAt": "2022-04-15T06:27:42.184Z",
            "updatedAt": "2022-04-15T06:27:42.184Z",
            "__v": 0
        }
    ],
    "June 2022": [
        {
            "date": "2022-06-22",
            "amount": "290",
            "description": "aaa",
            "category": "Investments",
            "createdAt": "2022-04-16T12:29:27.857Z",
            "updatedAt": "2022-04-16T12:29:27.857Z",
            "__v": 0
        }
    ]
}

我通过像这样的直接方法得到了它们:

this.monthlyCategories = Object.entries(this.monthlyObject)
.map((arrForEachMonth: Array<any>) => {
  return arrForEachMonth[1]
  .map((item: any) => item.category);
});

它工作正常,但我不喜欢重复代码,因为我会调用“数量,接受,类别”,所以我试图通过传递来减少代码作为映射值的函数参数 (item.name)。结果未定义。请告诉我我的错误是什么

const monthObjEntries = (name: string) => Object
  .entries(this.monthlyObject)
  .map((arrForEachMonth: Array<any>) => {
    
    return arrForEachMonth[1]
    .map((item: any) => item.name) // <- problem is here gives undefined
})

console.log(monthObjEntries('amount'));

其实我明白参数 name 不会变成 item.name。但是我不知道如何管理它..

你必须使用 item[name]。否则它将尝试访问不存在的 item 属性 name

return arrForEachMonth[1]
    .map((item: any) => item[name])