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

JavaScript中对象数组扁平化的实现方案优化咨询

当前实现的正确性

你的代码是正确的,输出完全符合预期。它针对给定的特定数据结构,手动遍历数组并构造带路径的键值对,逻辑清晰、结果准确,但存在明显局限性:

  • 硬编码了属性路径与具体属性,一旦数据结构发生变化(比如新增属性、嵌套层级调整),必须修改代码才能适配;
  • 仅能处理当前固定结构的对象,无法通用到其他嵌套对象/数组的扁平化场景。

通用扁平化实现(无需第三方库)

如果需要适配任意嵌套的对象和数组,可以编写递归的通用函数,自动生成带路径的键:

function flattenObject(obj, parentPath = '', result = {}) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const currentPath = parentPath ? `${parentPath}.${key}` : key;
      const value = obj[key];
      
      if (Array.isArray(value)) {
        value.forEach((item, index) => {
          flattenObject(item, `${currentPath}[${index}]`, result);
        });
      } else if (typeof value === 'object' && value !== null) {
        flattenObject(value, currentPath, result);
      } else {
        result[currentPath] = value;
      }
    }
  }
  return result;
}

// 使用示例
const data = {
  details: [
    { item_details: { number: "sdas", date: "28/07/2022" } },
    { item_details: { number: "hello", date: "28/07/2022" } }
  ]
};

console.log(flattenObject(data));

该函数会自动处理嵌套对象与数组,生成和你预期一致的键路径,可适配任何嵌套结构的数据。


第三方工具库推荐

如果不想手动实现通用逻辑,可以使用成熟工具库:

  1. flat:专门用于扁平化对象的轻量库,支持数组路径、自定义分隔符等配置

    • 安装:npm install flat
    • 使用示例:
      const flatten = require('flat');
      const result = flatten(data, { includeArrays: true });
      console.log(result);
      
      输出会完全匹配你的预期,自动将数组索引转换为[index]格式。
  2. Lodash:若项目已使用Lodash,可通过_.transform与_.toPath组合实现:

    const _ = require('lodash');
    
    function flattenWithLodash(obj) {
      return _.transform(obj, (result, value, key) => {
        const path = _.toPath(key);
        if (_.isPlainObject(value) || _.isArray(value)) {
          _.merge(result, flattenWithLodash(_.set({}, path, value)));
        } else {
          result[path.join('.').replace(/\.(\d+)/g, '[$1]')] = value;
        }
      }, {});
    }
    
    console.log(flattenWithLodash(data));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:11:07