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

求助:使用JavaScript reduce方法构造指定格式的ACL新对象

如何根据后端ACL响应构造指定格式的新数组

我来帮你搞定这个ACL格式转换的问题!咱们先把需求拆解开:需要把后端返回的每个权限对象做几个关键转换——属性名驼峰化、重新映射user_id/user_name为label/value,还要过滤掉值为false的权限字段,把剩下的转成指定的acl数组格式。

实现思路

  1. 遍历原始ACL数组,逐个处理每个用户权限对象
  2. 对每个对象:
    • 将蛇形命名的user_type转为驼峰式的userType
    • 把user_id赋值给label,user_name赋值给value
    • 过滤出所有值为true的权限字段(仅处理view/modify/remove,因为你的预期结果里没包含modify_acl),再把每个字段转成{value: 字段名, label: 首字母大写的字段名}的格式,组成acl数组
  3. 把所有处理后的对象收集成最终数组

代码实现(用map更直观)

map方法天生适合这种数组到数组的转换场景,代码可读性更高:

const originalAcl = [
  { "user_type":5, "user_id":"c7e5cb45ba764ad7ad29b5bdd4f12128", "user_name":"John", "view":true, "modify":false, "remove":false, "modify_acl":false },
  { "user_type":5, "user_id":"f673beac0245462f8c71066536049e72", "user_name":"Allan", "view":true, "modify":true, "remove":true, "modify_acl":false }
];

const formattedAcl = originalAcl.map(item => {
  // 提取并过滤有效权限字段
  const aclList = Object.entries(item)
    .filter(([key, val]) => {
      // 只保留指定的权限字段且值为true的
      const validPermissionKeys = ['view', 'modify', 'remove'];
      return validPermissionKeys.includes(key) && val === true;
    })
    .map(([key]) => ({
      value: key,
      label: key.charAt(0).toUpperCase() + key.slice(1) // 首字母大写生成label
    }));

  // 组装目标格式对象
  return {
    userType: item.user_type,
    label: item.user_id,
    value: item.user_name,
    acl: aclList
  };
});

console.log(formattedAcl);

如果坚持用reduce的版本

如果你习惯用reduce来处理,也可以这么写:

const formattedAclWithReduce = originalAcl.reduce((result, item) => {
  const aclList = Object.entries(item)
    .filter(([key, val]) => ['view', 'modify', 'remove'].includes(key) && val)
    .map(([key]) => ({
      value: key,
      label: key.charAt(0).toUpperCase() + key.slice(1)
    }));

  result.push({
    userType: item.user_type,
    label: item.user_id,
    value: item.user_name,
    acl: aclList
  });

  return result;
}, []);

关键细节说明

  • 特意指定了要处理的权限字段(view/modify/remove),避免把原始数据里的modify_acl或其他无关字段意外加入acl数组
  • 用Object.entries把对象转成键值对数组,方便后续的过滤和转换操作
  • 首字母大写的处理用了key.charAt(0).toUpperCase() + key.slice(1),简单高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:55:04