You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:09:02