Firestore get data()无法解析嵌套数组,如何获取完整嵌套数据?
解决Node.js中console.log截断嵌套数组显示的问题
这个问题我之前开发时也碰到过!Node.js的console.log默认会对嵌套较深的数组或对象做截断处理,用[Array]或[Object]来占位,确实没法看到完整的嵌套数据。给你几个快速有效的解决办法:
方法1:用console.dir()替代console.log()
console.dir是专门为查看对象结构设计的,你可以通过depth参数指定显示的层级深度,设为null就能展开所有嵌套内容:
const snapshot = await db.collection('matches').where('series', '==', 'Series-2').get(); snapshot.forEach((doc) => { console.dir(doc.data(), { depth: null }); });
方法2:转成格式化的JSON字符串
把对象转换成JSON字符串时,会完整保留所有嵌套结构,还能通过第三个参数设置缩进,让输出的格式更易读:
const snapshot = await db.collection('matches').where('series', '==', 'Series-2').get(); snapshot.forEach((doc) => { console.log(JSON.stringify(doc.data(), null, 2)); });
方法3:自定义递归打印函数(进阶可选)
如果需要更个性化的输出格式,你可以写一个简单的递归函数来遍历对象和数组,但一般前两种方法就足够满足需求了,这里给个示例参考:
function printFullData(obj) { if (typeof obj === 'object' && obj !== null) { if (Array.isArray(obj)) { console.log('['); obj.forEach((item, index) => { process.stdout.write(index > 0 ? ', ' : ' '); printFullData(item); }); console.log(']'); } else { console.log('{'); Object.entries(obj).forEach(([key, value], index) => { process.stdout.write(index > 0 ? ', ' : ' '); console.log(`"${key}": `); printFullData(value); }); console.log('}'); } } else { console.log(obj); } } // 使用自定义函数 const snapshot = await db.collection('matches').where('series', '==', 'Series-2').get(); snapshot.forEach((doc) => { printFullData(doc.data()); });
个人最推荐第二种方法,输出的格式化JSON结构清晰,复制出来也方便后续查看或处理。
内容的提问来源于stack exchange,提问作者coure2011
相关产品推荐
相关产品推荐

