首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JS对象中递归和异步转换DocumentReference

在JS对象中递归和异步转换DocumentReference
EN

Stack Overflow用户
提问于 2018-05-30 06:34:18
回答 1查看 74关注 0票数 0

我有这样的对象:

代码语言:javascript
复制
{
    "www.some-domain.com": {
        "key1": ["value1"],
        "data": {
            "d1": true,
            "d2": false,
            "d3": DocumentReference {...},
            "d4": []
        },
        "key2": "value2"
    }
}

我需要获得来自DocumentReference的异步数据。我遇到的问题是,我需要找到所有的DocumentReferences,将它们转换为.get().then((docSnap) => docSnap.data()),并将结果放在与DocumentReference相同的位置。

DocumentReference可以位于对象的所有级别。

你知道什么是完成这种事情的最好和最快的方法吗?

这样做的预期结果如下:

convert(data).then((convertedData) => {...})

转换后的数据如下:

代码语言:javascript
复制
{
    "www.some-domain.com": {
        "key1": ["value1"],
        "data": {
            "d1": true,
            "d2": false,
            "d3": {
                "c1": "v1",
                "c2": "v2",
                "c3": {
                    "z1": "zz2"
                }

            },
            "d4": []
        },
        "key2": "value2"
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-30 08:39:13

如果您使用async/await而不是常规的承诺,就会容易得多。

然后,您可以像这样递归地遍历对象:

代码语言:javascript
复制
// Using lodash just for `isArray` and `isObject`. You can use vanilla js if you want
const _ = require('lodash');

const getData = async ref => (await ref.get()).data();
// Please check this function. I just mocked DocumentReference so you might need to tweak it.
const isReference = ref => ref && ref instanceof DocumentReference;

// Traverse the object stepping into nested object and arrays.
// If we find any DocumentReference then pull the data before proceeding.
const convert = async data => {
    if (_.isArray(data)) {
        for (let i = 0; i < data.length; i += 1) {
            const element = data[i];

            if (isReference(element)) {
                // Replace the reference with actual data
                data[i] = await getData(data[i]);
            }

            // Note, we are passing data[i], not `element`
            // Because we want to traverse the actual data not the DocumentReference
            await convert(data[i]);
        }

        return data;
    }

    if (data && _.isObject(data)) {
        const keys = Object.keys(data);

        for (let i = 0; i < keys.length; i += 1) {
            const key = keys[i];
            const value = data[key];

            if (isReference(value)) {
                data[key] = await getData(value);
            }

            // Same here. data[key], not `value`
            await convert(data[key])
        }

        return data;
    }
}

// You can use it like this
const converted = await convert(dataObject);
// Or in case you don't like async/await:
convert(dataObject).then(converted => ...);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50597797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档