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

如何用Lodash生成指定格式的键值对对象?

实现方式:用Lodash将ids数组转为目标对象

嘿,这事儿用Lodash有好几种简洁的实现方式,我给你分享几个最常用的:

方法1:_.fromPairs + _.map 组合

这是最直观的方式——先把每个id映射成「键-值对」数组,再转成对象:

const _ = require('lodash');
const ids = ["1234", "5678", "0987", "6543"];

const result = _.fromPairs(
  _.map(ids, id => [id, { workId: null }])
);

逻辑说明:

  • _.map(ids, id => [id, { workId: null }]) 会把原数组转成 [["1234", { workId: null }], ["5678", { workId: null }], ...] 的格式
  • _.fromPairs 负责把这种键值对数组直接转换成目标对象

方法2:_.reduce 手动构建

如果你更喜欢底层一点的遍历控制,用_.reduce也很顺手:

const _ = require('lodash');
const ids = ["1234", "5678", "0987", "6543"];

const result = _.reduce(ids, (acc, id) => {
  acc[id] = { workId: null };
  return acc;
}, {});

逻辑说明:

  • 初始化一个空对象{}作为累加器acc
  • 遍历每个id,给累加器添加对应的键和值
  • 最后返回构建好的累加器,就是目标对象

方法3:_.keyBy + _.mapValues 组合

这个方式稍微绕一点,但也能实现:

const _ = require('lodash');
const ids = ["1234", "5678", "0987", "6543"];

const result = _.mapValues(
  _.keyBy(ids, id => id), 
  () => ({ workId: null })
);

逻辑说明:

  • _.keyBy(ids, id => id) 先把数组转成 { "1234": "1234", "5678": "5678", ... } 的对象
  • _.mapValues 把每个值替换成 { workId: null },得到最终结果

这几种方法都能达到你的需求,个人推荐第一种,代码最简洁直观~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:22:52