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

如何在JavaScript中展平含动态键值对子数组的数组对象?

扁平化包含Attributes子数组的对象数组

要实现把每个父对象里的Attributes子数组键值对迁移到父对象中,我们可以用JavaScript的map和reduce方法组合来完成这个转换,代码简洁且易读:

const inputArray = [
  {
    "Attributes": [
      { "Name": "profile", "Value": "UI" },
      { "Name": "phone_number", "Value": "+91123456789" },
      { "Name": "email", "Value": "to_test@test.in" }
    ],
    "UserCreateDate": 1524465619.163,
    "Username": "neeraj"
  }
];

const flattenedArray = inputArray.map(user => {
  // 分离出Attributes和其他原始属性
  const { Attributes, ...restOfUser } = user;
  // 将Attributes数组转换为键值对对象
  const attributesMap = Attributes.reduce((acc, attribute) => {
    acc[attribute.Name] = attribute.Value;
    return acc;
  }, {});
  // 合并原始属性和转换后的Attributes键值对
  return { ...restOfUser, ...attributesMap };
});

console.log(flattenedArray);

代码解释:

  • map遍历数组:逐个处理输入数组里的每个用户对象,确保每个对象都被扁平化
  • 对象解构分离属性:用{ Attributes, ...restOfUser }把原对象中不需要保留的Attributes数组提取出来,剩下的属性(比如UserCreateDate、Username)都存在restOfUser里
  • reduce转换Attributes:遍历Attributes数组,把每个{Name, Value}格式的对象转换成普通的键值对,最终生成一个包含所有属性的对象
  • 合并对象:用扩展运算符...把原始属性对象和转换后的Attributes对象合并,得到最终的扁平化对象

健壮性优化(可选)

如果你的输入数组中可能存在Attributes为空或者未定义的情况,可以给Attributes设置默认值,同时过滤掉无效的键值对:

const flattenedArray = inputArray.map(user => {
  // 给Attributes设置默认空数组,避免reduce报错
  const { Attributes = [], ...restOfUser } = user;
  const attributesMap = Attributes.reduce((acc, attribute) => {
    // 只处理有有效Name和Value的属性
    if (attribute.Name && attribute.Value !== undefined) {
      acc[attribute.Name] = attribute.Value;
    }
    return acc;
  }, {});
  return { ...restOfUser, ...attributesMap };
});

运行这段代码后,就能得到你期望的输出数组啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:58:24