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

时间:2018-05-30 06:34:19

标签: javascript ecmascript-6 google-cloud-firestore

我有这种类型的对象:

{
    "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"
    }
}

1 个答案:

答案 0 :(得分:1)

如果您使用async/await而不是常规承诺,情况会更容易。

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



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