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

如何将含数字下标的JavaScript对象键转换为数组结构?

扁平化JS对象转嵌套结构(支持数字下标方括号)

原始扁平化对象

{
  name: "Gold's Gym Venice",
  "categories[0].alias": "gyms",
  "categories[0].title": "Gyms",
  "categories[1].alias": "healthtrainers",       
  "categories[1].title": "Trainers",
  "location.state": "CA",
  "location.city": "Venice",
  "location.zip_code": "90291",
  "location.display_address[0]": "360 Hampton Dr",
  "location.display_address[1]": "Venice, CA 90291"
}

目标嵌套结构

{
    name: "Gold's Gym Venice",
    categories: [
        { alias: "gyms", title: "Gyms" },
        { alias: "healthtrainers", title: "Trainers" }
    ],
    location: {
      state: "CA",
      city: "Venice",
      zip_code: "90291",
      display_address: [ "360 Hampton Dr", "Venice, CA 90291" ]
    }
}

最优处理方案

可以实现一个通用解析函数,专门处理包含.和[数字]格式的键,核心是拆解每个键的路径,区分对象属性与数组下标:

function flattenToNested(obj) {
  const nested = {};

  Object.entries(obj).forEach(([key, value]) => {
    // 拆分路径:匹配属性名或数组下标(如[0])
    const pathParts = key.match(/([^\.\[\]]+)|\[(\d+)\]/g).filter(Boolean);
    let current = nested;

    pathParts.forEach((part, index) => {
      if (part.startsWith('[')) {
        // 处理数组下标
        const idx = parseInt(part.slice(1, -1), 10);
        const arrayName = pathParts[index - 1];
        // 确保父属性是数组类型
        if (!Array.isArray(current[arrayName])) {
          current[arrayName] = [];
        }
        current = current[arrayName];

        if (index === pathParts.length - 1) {
          // 路径终点,直接赋值
          current[idx] = value;
        } else {
          // 后续还有属性,初始化当前下标位置为对象
          if (!current[idx]) {
            current[idx] = {};
          }
          current = current[idx];
        }
      } else {
        // 处理普通对象属性
        if (index === pathParts.length - 1) {
          current[part] = value;
        } else {
          // 根据下一个片段类型,初始化当前属性为数组或对象
          const nextPart = pathParts[index + 1];
          if (!current[part]) {
            current[part] = nextPart.startsWith('[') ? [] : {};
          }
          current = current[part];
        }
      }
    });
  });

  return nested;
}

使用示例

const flatObj = {
  name: "Gold's Gym Venice",
  "categories[0].alias": "gyms",
  "categories[0].title": "Gyms",
  "categories[1].alias": "healthtrainers",       
  "categories[1].title": "Trainers",
  "location.state": "CA",
  "location.city": "Venice",
  "location.zip_code": "90291",
  "location.display_address[0]": "360 Hampton Dr",
  "location.display_address[1]": "Venice, CA 90291"
};

// 转换后得到目标结构
console.log(flattenToNested(flatObj));

核心逻辑说明

  1. 路径拆分:通过正则把每个键拆分为属性名或数组下标片段,比如categories[0].alias会拆分为['categories', '[0]', 'alias'];
  2. 类型区分处理:
    • 遇到数组下标时,先确保父属性为数组类型,再根据后续路径初始化下标位置的结构或直接赋值;
    • 遇到普通属性时,根据下一个路径片段的类型,提前初始化对应的数组或对象结构;
  3. 终点赋值:遍历到路径最后一个片段时,将对应的值赋值到目标位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:17:52