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

JS中动态将对象属性分组为嵌套对象的实现方法

对象数组属性分组实现方案

我有一个包含多个条目的对象数组,希望动态将其中部分属性进行分组。

原对象结构如下:

[{
    Beton: "120",
    Asfalt: "80",
    ConstructionId: "(10)4",
    Name: "Pælefundamenter og brøndfundamenter",
    ParentId : "10",
    ParentName: "Bygningsbasis, terræn"
}]

期望转换为如下结构:

[{
    ConstructionId: "(10)4",
    Name: "Pælefundamenter og brøndfundamenter",
    ParentId : "10",
    ParentName: "Bygningsbasis, terræn",
    materialLifeTime: {
        Beton: "120",
        Asfalt: "80",
    }
}]

实现方法

场景1:明确知道需要分组的属性名

如果已经确定哪些属性要归入materialLifeTime,可以直接指定属性列表进行过滤:

// 原始数据数组
const originalData = [
  {
    Beton: "120",
    Asfalt: "80",
    ConstructionId: "(10)4",
    Name: "Pælefundamenter og brøndfundamenter",
    ParentId : "10",
    ParentName: "Bygningsbasis, terræn"
  }
];

// 定义需要分组的属性集合
const materialKeys = ['Beton', 'Asfalt'];

// 遍历转换每个对象
const transformedData = originalData.map(item => {
  const materialLifeTime = {};
  const restProps = {};

  // 拆分原对象的键值对
  Object.entries(item).forEach(([key, value]) => {
    if (materialKeys.includes(key)) {
      materialLifeTime[key] = value;
    } else {
      restProps[key] = value;
    }
  });

  // 合并剩余属性和分组后的对象
  return { ...restProps, materialLifeTime };
});

console.log(transformedData);

场景2:动态排除不需要分组的属性

如果需要保留的属性是固定的,剩余属性全部归入materialLifeTime,可以反过来定义保留的属性列表:

// 原始数据数组
const originalData = [
  {
    Beton: "120",
    Asfalt: "80",
    ConstructionId: "(10)4",
    Name: "Pælefundamenter og brøndfundamenter",
    ParentId : "10",
    ParentName: "Bygningsbasis, terræn"
  }
];

// 定义不需要分组的属性集合
const preservedKeys = ['ConstructionId', 'Name', 'ParentId', 'ParentName'];

// 遍历转换每个对象
const transformedData = originalData.map(item => {
  const materialLifeTime = {};
  const restProps = {};

  // 拆分原对象的键值对
  Object.entries(item).forEach(([key, value]) => {
    if (preservedKeys.includes(key)) {
      restProps[key] = value;
    } else {
      materialLifeTime[key] = value;
    }
  });

  // 合并剩余属性和分组后的对象
  return { ...restProps, materialLifeTime };
});

console.log(transformedData);

核心逻辑说明

  • 使用Array.map()遍历原数组,对每个对象进行转换
  • 通过Object.entries()将对象拆分为键值对数组,方便遍历判断
  • 根据预设的属性列表,将属性分配到对应的对象中
  • 最后使用对象展开运算符...合并剩余属性和分组后的对象,返回新的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:15:40