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

如何使用Lodash将键值对转换为指定结构的对象?

使用Lodash转换键值对为指定结构的最优方案

嘿,这个需求用Lodash实现起来非常直观,我推荐两种高效且常用的写法,你可以根据自己的代码风格选择:

方法一:直接使用_.map遍历对象

Lodash的_.map方法支持直接遍历对象的键值对,第二个回调函数可以拿到每个属性的值和对应的键,刚好可以直接构造你需要的结构:

const _ = require('lodash');

const maps = { 
  "Recipe1" : ["Sugar", "Milk", "Bread"], 
  "Recipe2" : ["Rice", "Salt", "Carrots"] 
};

// 核心转换代码
const recipes = _.map(maps, (ingredients, name) => ({
  name,
  ingredients
}));

console.log(recipes);
// 输出:
// [
//   { name: "Recipe1", ingredients: ["Sugar", "Milk", "Bread"] },
//   { name: "Recipe2", ingredients: ["Rice", "Salt", "Carrots"] }
// ]

这种写法最简洁,不需要额外的中间步骤,_.map会自动帮你遍历整个对象,时间复杂度是O(n),属于最优的实现方式。

方法二:链式调用(适合复杂数据处理场景)

如果你的代码习惯用链式风格,或者后续还要对数据做更多操作,可以用_.entries先把对象转成键值对数组,再通过_.map转换结构:

const recipes = _.chain(maps)
  .entries() // 把对象转成 [["Recipe1", [...]], ["Recipe2", [...]]]
  .map(([name, ingredients]) => ({ name, ingredients })) // 解构赋值构造目标对象
  .value(); // 取出链式调用的最终结果

这种写法的好处是可以在链式中无缝添加其他操作(比如过滤、排序等),可读性更强,性能和第一种方法完全一致。

两种方法都是Lodash处理这类转换的最优选择,没有性能差异,主要看你个人的代码风格偏好~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:15:26