繁体   English   中英

如何递归构建嵌套的 object

[英]How to recursively build a nested object

我很难弄清楚这一点。 我正在尝试在递归 function 中构建一个 object ,它将在每次调用时在键“next”中添加一些数据的嵌套副本,直到它达到一定数量的深度。 这是一个代码示例(当然不起作用) 对代码进行了注释以帮助理解我的目标。

function recursiveDoSomethingWithObj(base, index) {

    // making default values here since setting them at params didnt seem to work.
    if (!index) index = 0
    if (!base) base = {}

    // just adding some data for the example
    base.someData = "someData"

    // printing to get a look
    console.log(`object ${JSON.stringify(base)}`);

    // preparing the next nested level
    base.next = {}

    // this is the exit condition - i want to iterate as many times as set here, in this case 2
    if (index < 2) {
        // increment index to eventually exit
        index = index + 1
        // call function again 
        return recursiveDoSomethingWithObj(base.next, index)
    }
    else {
        // eventually exit with the nested object
        return base
    }

}

recursiveDoSomethingWithObj()

最终发生的事情是在第一次迭代之后我通过 base.next 的下一个迭代我希望引用会坚持下去,我仍然会每次都在更深层次上引用基本 object,但它被认为是全新 object 每次迭代。 任何帮助将不胜感激,如果我需要更清楚地了解我的要求,请告诉我。 我希望的快速示例:这只是一个示例,在我的实际应用程序中,这是一个更大的 function,它每次都输入不同的数据,并且除了“someData”键之外还有多个键

{
    base: {
        someData:"some type of string",
        next:{
            someData:"a different string from the one on the earlier level",
            next:{
                someData:"another string with other words in it",
                next:{}
            }
        }
    }
}

依此类推,取决于我将其设置为在退出条件下运行的深度。 感谢任何帮助者。

当您已经有一个包含要转换为嵌套结构的数据的数组时,请使用reduceRight从内向外构建嵌套结构:

 let data = ["a", "b", "c"]; let next = data.reduceRight((next, a) => ({ a, next }), {}); let result = { base: next }; console.log(result);

如果您以异步方式获取数据,例如从请求中获取数据,那么您将需要使用异步编码模式:

 async function createList(url, count) { let result = {}; let last = result; for (let i = 1; i <= count; i++) { let response = await fetch(url + i); let { title } = await response.json(); last.title = title; last = last.next = {}; } return result; } let url = "https://jsonplaceholder.typicode.com/posts/"; createList(url, 3).then(base => { let result = { base }; console.log(result); });

暂无
暂无

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

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