我有一组键/值对,我想将它们转换为对象。使用 lodash 执行此操作的最佳方法是什么。
maps: {
"Recipe1" : ["Sugar", "Milk", "Bread"],
"Recipe2" : ["Rice", "Salt", "Carrots"]
}
寻找如下所示的输出
{
name: "Recipe1",
ingredients: ["Sugar", "Milk", "Bread"]
},
{
name: "Recipe2",
ingredients: ["Rice", "Salt", "Carrots"]
}
最佳答案
在没有 lodash 的情况下,使用 Object.entries()
做起来非常简单, Array.prototype.map()
, 一个 destructured parameter , 和 shorthand property names对于返回的对象:
const maps = {
"Recipe1" : ["Sugar", "Milk", "Bread"],
"Recipe2" : ["Rice", "Salt", "Carrots"]
}
const output = Object.entries(maps).map(
([name, ingredients]) => ({ name, ingredients })
)
console.log(output)
关于javascript - 使用 lodash 将键/值对转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399034/