gpt4 book ai didi

javascript - 循环遍历对象并查找指定属性

转载 作者:行者123 更新时间:2023-12-01 03:29:49 24 4
gpt4 key购买 nike

我有一个对象数组。典型的对象如下所示:

{
id: x
name: y
employeeInfo: {
employeeNumber: x
startDate: x
}
salary: x
}

现在我尝试循环它并获取姓名、员工编号和薪水。

要在循环中使用的我的列变量是:

public columns: Array<any> = [
{title: 'id', name: 'id'},
{title: 'employeeInfo.employeeNumber', name: 'employeeInfo.employeeNumber'},
{title: 'salary', name: 'salary'}]

我正在尝试循环

item[column.name]

但是这当然会导致 item['emplyeeInfo.employeeNumber'],从而导致未定义。

有人可以帮忙吗?

最佳答案

您可以拆分列名称并减少,例如:

column.name.split('.').reduce((res, part) => res[part], item)

split返回一个数组(在我们的例子中 ['employeeInfo', 'employeeNumber']),这样我们就可以 reduce该数组使用 item 作为 initialValue

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

关于javascript - 循环遍历对象并查找指定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44590747/

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