You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在对象数组中通过嵌套对象键取值,修复对应TypeScript工具函数

问题原因

原有代码没有对prop数组的元素做类型区分,统一将所有元素当做对象顶层键名读取属性,因此自定义的嵌套取值函数无法生效。

修复方案

遍历prop数组元素时增加类型判断:

  • 如果当前元素是函数类型,直接调用函数并传入当前行对象获取返回值
  • 如果当前元素是键名类型,按原有逻辑读取对象对应属性值
完整修复后代码
resultToArray<T>(
    data: T[],
    prop: (keyof T | ((row: T) => string))[] = []
): string[][] {
    // data: [{id: 1, name: 'first'}, {id: 2, name: 'second'}] -> [[1, 'first'], [2, 'second']]
    // prop: ['id', 'name']
    if (prop.length === 0) {
        return data.map(Object.values);
    } else {
        const output = data.map(d => {
            const a: string[] = [];
            for (let i = 0; i < prop.length; i++) {
                const currentProp = prop[i];
                // 新增类型判断逻辑
                if (typeof currentProp === 'function') {
                    a.push(currentProp(d));
                } else {
                    a.push(d[currentProp] as string);
                }
            }
            return a;
        });
        return output
    }
}
验证结果

使用你给出的示例输入调用函数,即可得到预期输出[['Name', 'Locale'], ['Name2', 'Locale2']]。

如果你需要支持非字符串类型的返回值,可以将函数返回值类型修改为(T[keyof T] | ReturnType<(typeof prop)[number]>)[][],去掉string[]的类型限制即可。

内容的提问来源于stack exchange,提问作者Daniyar Changylov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:15:05