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

如何在JavaScript中将对象数组转换为嵌套结构的单一对象

如何将对象数组合并为嵌套层级结构的单一对象?

我有一个对象数组,需要将其合并为具备父子层级结构的单一对象。此前尝试过创建空对象并用for循环逐个添加内容,但因嵌套层级较多未成功;也用过lodash的_.flatten方法,同样没达到预期效果。

输入示例

let array = [
    {
        "Gender": "male",
        "Type": "backpacks",
        "Key": "size",
        "Values": "small,large,medium"
    },
    {
        "Gender": "male",
        "Type": "backpacks",
        "Key": "strap",
        "Values": "padded,non-padded"
    },
    {
        "Gender": "female",
        "Type": "backpacks",
        "Key": "pocket",
        "Values": "multiple,zip,buckle"
    },
    {
        "Gender": "female",
        "Type": "backpacks",
        "Key": "size",
        "Values": "small,large,medium"
    },
    {
        "Gender": "female",
        "Type": "sunglasses",
        "Key": "size",
        "Values": "XL,XXL,XXL"
    },
    {
        "Gender": "female",
        "Type": "sunglasses",
        "Key": "color",
        "Values": "red,black,yellow"
    }
]

期望输出

let obj = {
    "male": {
        "backpacks": {
            "size": "small,large,medium",
            "strap": "padded,non-padded"
        }
    },
    "female": {
        "backpacks": {
            "pocket": "multiple,zip,buckle",
            "size": "small,large,medium"
        },
        "sunglasses": {
            "size": "XL,XXL,XXL",
            "color": "red,black,yellow"
        }
    }
}

解决方案

原生JavaScript实现(使用Array.reduce)

通过reduce遍历数组,逐步构建嵌套层级。每次迭代时检查当前层级的对象是否存在,不存在则创建空对象,最后赋值对应属性:

const result = array.reduce((acc, item) => {
    // 确保Gender层级存在
    if (!acc[item.Gender]) {
        acc[item.Gender] = {};
    }
    // 确保Type层级存在
    if (!acc[item.Gender][item.Type]) {
        acc[item.Gender][item.Type] = {};
    }
    // 赋值Key-Values
    acc[item.Gender][item.Type][item.Key] = item.Values;
    return acc;
}, {});

console.log(result);

Lodash实现(使用_.set)

如果使用Lodash,不需要手动检查层级,_.set方法可以直接设置嵌套属性,不存在的层级会自动创建:

const _ = require('lodash');

const result = {};
array.forEach(item => {
    // 构建路径:[Gender, Type, Key]
    const path = [item.Gender, item.Type, item.Key];
    _.set(result, path, item.Values);
});

console.log(result);

这两种方法都能高效地将数组转换为目标嵌套结构,解决手动循环时层级判断繁琐的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:01:05