繁体   English   中英

如何递归访问 object 值?

[英]How to recursively get access to object values?

我有一个带有递归对象的数组,如下所示:

export const a: A = [
    {
        person: [
            {
                person: [{
                    person: [],
                    rating: 512,
                    justNumbers: [30, 15, 327]
                },
                    {
                        person: [
                            {
                                person: [],
                                rating: 538,
                                justNumbers: [13, 55, 643]
                            },
                            {
                                person: [],
                                rating: 964,
                                justNumbers: [314, 523, 512]
                            }
                        ],
                        rating: 413,
                        justNumbers: [876, 541, 623]
                    }],
                rating: 176,
                justNumbers: [842, 812,643]
            }
        ],
        rating: 235,
        justNumbers: [33, 565, 73]
    }];

我需要创建一个 function 以递归方式对所有评分求和,并从每个 justNumbers 数组中的所有数字创建一个数字数组,该数组按升序排序。

  const recursiveNumbersSearch = (obj: object, targetKey: string, getSum = []) => {
    const r = getSum;
    Object.keys(obj).forEach(key => {
        const value: any = obj[key];
        if (key === targetKey && typeof value !== 'object') {
            r.push(value)
        } else if (typeof value === 'object') {
            recursiveNumbersSearch(value, targetKey, r);
        }
    })
    return getSum
}

function sumArray (arr : number[]): number {
    let arraySum: number = 0;
    for (let i = 0; i<= arr.length - 1; i++) {
        arraySum = arr[i] + arraySum;
    }
    return arraySum;
}

我这样做了,它计算得很好,但是,编译器错误很少:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.

Argument of type 'any' is not assignable to parameter of type 'never'.

第一个用于字符串:

const value: any = obj[key];

当第二个指的是:

r.push(value)

我有点困惑,因为如果我用节点运行编译的 JS 文件,它会正确计算总和,但它确实指向这两个错误。

另一方面,我无法使用 recursiveNumberSearch 方法推送 justNumbers 的 arrays 。

我认为您遇到 arrays 问题的原因是因为您测试typeof value === 'object' ,但如果value在数组中,那将是正确的。

在这里,我写了我认为是更简单的recursiveNumbersSearch版本,称为deepProp 它接受一个属性名称并返回一个 function,它接受一个 object 并进行深度优先遍历,在找到的任何地方检索命名的属性。 然后,我们可以使用它对简单的函数进行分层,以对rating属性进行求和,或者对justNumbers进行展平和排序,如下所示:

 const deepProp = (prop) => ({[prop]: p, ...rest}) => p == undefined? Object.values (rest).flatMap (deepProp (prop)): [p, ... deepProp (prop) (rest)] const a = [{person: [{person: [{person: [], rating: 512, justNumbers: [30, 15, 327]}, {person: [{person: [], rating: 538, justNumbers: [13, 55, 643]}, {person: [], rating: 964, justNumbers: [314, 523, 512]}], rating: 413, justNumbers: [876, 541, 623]}], rating: 176, justNumbers: [842, 812, 643]}], rating: 235, justNumbers: [33, 565, 73]}] console.log (deepProp ('rating') (a)) console.log (deepProp ('justNumbers') (a)) const sum = (ns) => ns.reduce ((a, b) => a + b, 0) const sumRatings = (o) => sum (deepProp ('rating') (o)) const organizeNumbers = (o) => deepProp ('justNumbers') (o).flat ().sort ((a, b) => a - b) console.log (sumRatings (a)) console.log (organizeNumbers (a))
 .as-console-wrapper {max-height: 100%;important: top: 0}

对于您的 Typescript 错误,恐怕我无能为力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM