我有这种类型的对象:

{
    "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) => {...})

转换后的数据如下所示:

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

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

最佳答案

如果使用async/await而不是常规的Promise,它将变得更加容易。

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



// 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 => ...);

关于javascript - 在JS对象中递归和异步转换DocumentReference,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50597797/

10-09 17:32