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

如何将JavaScript对象数组按指定键转换为值为数组的键值对

问题原因

你写的reduce逻辑每次迭代都直接用当前值覆盖对应key的内容,且没有做姓名拼接、数组追加的处理,因此每个key最终只会保留最后一个匹配项的值。

修正后代码

const convertArrayToObject = (array, key) => {
  const initialValue = {};
  // 第一步:按指定key分组,拼接姓名存入数组
  const groupedResult = array.reduce((obj, item) => {
    const currentKey = item[key];
    // 对应key不存在时先初始化空数组
    if (!obj[currentKey]) {
      obj[currentKey] = [];
    }
    // 拼接全名追加到对应数组中
    obj[currentKey].push(`${item.firstName} ${item.lastName}`);
    return obj;
  }, initialValue);

  // 第二步:对每个分组的姓名按字母顺序排序,匹配期望的输出顺序
  Object.values(groupedResult).forEach(nameList => nameList.sort());

  return groupedResult;
};

// 测试调用
const result = convertArrayToObject(contacts, 'account');

调用后输出的result和你给出的预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:36:03