简体   繁体   English

如何递归访问 object 值?

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

I have an array with recursive objects which looks like this:我有一个带有递归对象的数组,如下所示:

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]
    }];

I need to create a function to sum all ratings in recursive way and to create an array of numbers from all numbers in every justNumbers array, which is sorted in ascending order.我需要创建一个 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;
}

I did this and it counts the sum pretty well, however, there are few compiler errors which are:我这样做了,它计算得很好,但是,编译器错误很少:

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'.

First one goes for string:第一个用于字符串:

const value: any = obj[key];

When second one refers to:当第二个指的是:

r.push(value)

I am a little bit confused, because if I run compiled JS file with node it properly counts the sum, however it does point at those two errors.我有点困惑,因为如果我用节点运行编译的 JS 文件,它会正确计算总和,但它确实指向这两个错误。

From the other hand I am unable to push arrays of justNumbers using the recursiveNumberSearch method.另一方面,我无法使用 recursiveNumberSearch 方法推送 justNumbers 的 arrays 。

I think the reason you're having problems with the arrays is because you test typeof value === 'object' , but that will be true if value in an Array.我认为您遇到 arrays 问题的原因是因为您测试typeof value === 'object' ,但如果value在数组中,那将是正确的。

Here, I write what I think is a simpler version of recursiveNumbersSearch , called deepProp .在这里,我写了我认为是更简单的recursiveNumbersSearch版本,称为deepProp It takes a property name and returns a function that takes an object and does a depth-first traversal, retrieving the named property wherever it's found.它接受一个属性名称并返回一个 function,它接受一个 object 并进行深度优先遍历,在找到的任何地方检索命名的属性。 We can then use that to layer on simple functions to sum the rating properties or flatten and sort the justNumbers ones, like this:然后,我们可以使用它对简单的函数进行分层,以对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}

I'm afraid I have nothing to offer for your Typescript errors.对于您的 Typescript 错误,恐怕我无能为力。

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

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