我有这样的对象:
{
"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"
}
}发布于 2018-05-30 08:39:13
如果您使用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 => ...);
https://stackoverflow.com/questions/50597797
复制相似问题