Skip to content Skip to sidebar Skip to footer

Convert Recursively And Asynchronous Documentreference In An Js Object

I have this type of object: { 'www.some-domain.com': { 'key1': ['value1'], 'data': { 'd1': true, 'd2': false, 'd3': Document

Solution 1:

It's going to be much easier if you use async/awaits instead of regular promises.

Then you can traverse the object recursively like this:

// Using lodash just for `isArray` and `isObject`. You can use vanilla js if you wantconst _ = 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.constisReference = ref => ref && ref instanceofDocumentReference;

// 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] = awaitgetData(data[i]);
            }

            // Note, we are passing data[i], not `element`// Because we want to traverse the actual data not the DocumentReferenceawaitconvert(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] = awaitgetData(value);
            }

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

        return data;
    }
}

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

Post a Comment for "Convert Recursively And Asynchronous Documentreference In An Js Object"