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

如何将指定对象数组转换为目标结构的JavaScript对象?

解决方案

根据你给出的输入数组和目标结构,核心是建立slug到目标键以及渠道到权重值的映射关系,然后通过遍历计算得到结果。以下是完整的实现代码:

// 你的原始通知数组
const notifications = [
  { slug: 'invoice', display: 'Invoice', channels: { sms: true, email: false } },
  { slug: 'payment', display: 'Payment', channels: { sms: true, email: true } },
  { slug: 'manual_reminder', display: 'Manual Reminder', channels: { sms: true, email: false } },
  { slug: 'automatic_reminder', display: 'Automatic Reminder', channels: { sms: true, email: false } }
];

// 1. 定义slug与目标对象键的映射
const slugToTargetKey = {
  invoice: '10',
  payment: '20',
  manual_reminder: '30',
  automatic_reminder: '31'
};

// 2. 定义渠道对应的权重值(用于计算目标值)
const channelWeightMap = {
  sms: 1,
  email: 2
};

// 3. 执行转换逻辑
const result = notifications.reduce((acc, current) => {
  // 找到当前项对应的目标键
  const targetKey = slugToTargetKey[current.slug];
  // 计算启用渠道的权重总和
  const totalWeight = Object.entries(current.channels)
    .filter(([_, isEnabled]) => isEnabled) // 过滤出启用的渠道
    .reduce((sum, [channel]) => sum + channelWeightMap[channel], 0); // 累加权重
  // 存入结果对象
  acc[targetKey] = totalWeight;
  return acc;
}, {});

console.log(result);
// 输出:{"10": 1, "20": 3, "30": 1, "31": 1}

代码说明

  • 映射关系定义:通过slugToTargetKey将每个通知类型的slug对应到目标对象的字符串键;channelWeightMap给每个渠道分配权重,payment同时启用sms和email,权重1+2=3,刚好匹配目标中的"20":3。
  • reduce遍历:用Array.reduce代替forEach,更简洁地构建结果对象,避免额外的变量声明。
  • 灵活扩展:如果后续新增通知类型或渠道,只需要更新两个映射对象即可,不需要修改核心遍历逻辑。

如果你的转换逻辑不是基于权重求和,而是其他规则(比如统计同类型数量),可以补充你的具体需求,我再帮你调整代码!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:54:18