如何在map()循环内嵌套遍历配置数组,动态生成日志格式化内容
解决方案
你可以先把arr配置调整为「字段展示名+取值路径数组」的结构,再写一个通用的按路径取值工具函数,就能完全替代硬编码逻辑,完整可运行代码如下:
const dedent = require('dedent'); // 配置数组:[展示名, 取值路径数组],后续新增字段只要加这一项即可 const arr = [ ['Log entry ID', ['_id']], ['UUID', ['_source', 'uuid']], ['Timestamp', ['_source', '@timestamp']], ]; // 通用取值工具:根据路径数组从目标对象中取对应值 const getValueByPath = (target, path) => { return path.reduce((res, key) => res?.[key], target); } const docs = [ {'_id': 1,'_source': {'uuid': 2,'@timestamp': 3}}, {'_id': 4,'_source': {'uuid': 5,'@timestamp': 6}}, ]; const description = dedent` ================================================ ${ docs.map((element) => [ // 遍历配置数组动态生成每一行内容 ...arr.map(([label, path]) => `${label}: ${getValueByPath(element, path)}`), '' // 加空元素实现每个日志块末尾的换行 ].join('\n')).join('--------------------\n') } `; console.log(description);
运行后输出和你预期的格式完全一致,后续如果需要新增/删减日志展示字段,只需要修改arr配置数组即可,不需要调整核心渲染逻辑。
内容的提问来源于stack exchange,提问作者Sandra Schlichting
相关产品推荐
相关产品推荐

