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

JavaScript如何将嵌套对象、字符串、数组转换为无序列表

你的递归思路完全正确,这种数组、对象混合的任意深度嵌套结构,用递归处理是最清晰的方案。
先对齐你给出的样例输出,梳理出统一的遍历规则:

  1. 字符串、数字这类基础值,直接作为当前层级的列表项渲染
  2. 遇到数组/对象这类引用类型时,遍历其内部的元素/属性值:如果内部值是基础类型,就在当前层级输出;如果内部值还是引用类型,就增加一级缩进,递归处理该值
  3. 每级缩进用3个空格,和你给出的样例格式对齐

可直接运行的参考实现如下:

// 原始数据源
const data = ["test", { testone: "check", filter: [{ testtwo: "ignore", cancel: ["3.2"]}]}, "testthree"];

/**
 * 递归生成嵌套无序列表
 * @param {any} current 当前处理的节点
 * @param {number} level 当前缩进层级,默认从0(顶格)开始
 * @returns {string} 拼接完成的列表字符串
 */
function buildNestedList(current, level = 0) {
  const indentPerLevel = '   '; // 单级缩进长度,可按需调整
  const currentIndent = indentPerLevel.repeat(level);
  let output = '';

  // 基础类型:直接拼接当前层列表项
  if (typeof current !== 'object' || current === null) {
    return `${currentIndent}. ${current}\n`;
  }

  // 数组分支:遍历所有元素
  if (Array.isArray(current)) {
    current.forEach(item => {
      // 元素是引用类型则缩进+1,否则保持当前层级
      const nextLevel = (typeof item === 'object' && item !== null) ? level + 1 : level;
      output += buildNestedList(item, nextLevel);
    });
    return output;
  }

  // 对象分支:遍历所有属性值(样例不需要输出键名,所以直接取value)
  Object.values(current).forEach(val => {
    // 属性值是引用类型则缩进+1,否则保持当前层级
    const nextLevel = (typeof val === 'object' && val !== null) ? level + 1 : level;
    output += buildNestedList(val, nextLevel);
  });
  return output;
}

// 调用函数生成结果
const result = buildNestedList(data);
console.log(result);

运行后输出和你要求的格式完全一致:

. test
   . check
      . ignore
         . 3.2
. testthree

如果后续需要调整格式(比如要显示对象键名、修改缩进符号、调整列表标记),只需要修改对应分支的字符串拼接逻辑即可,递归的核心框架不需要改动。

内容的提问来源于stack exchange,提问作者eilrahc301

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 19:09:21