我有一组键/值对,我想将它们转换为对象。使用lodash做到这一点的最佳方法是什么。
maps: {
"Recipe1" : ["Sugar", "Milk", "Bread"],
"Recipe2" : ["Rice", "Salt", "Carrots"]
}
寻找下面的内容
{
name: "Recipe1",
ingredients: ["Sugar", "Milk", "Bread"]
},
{
name: "Recipe2",
ingredients: ["Rice", "Salt", "Carrots"]
}
答案 0 :(得分:4)
如果没有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)

答案 1 :(得分:2)
您可以使用Object.entries()
获取一组键/值对。使用Array.map()
迭代对数组。使用destructuring assignment获取name
和ingredients
参数,并使用shorthand property names创建结果对象:
const maps = {
"Recipe1" : ["Sugar", "Milk", "Bread"],
"Recipe2" : ["Rice", "Salt", "Carrots"]
};
const result = Object.entries(maps)
.map(([name, ingredients]) => ({ name, ingredients }));
console.log(result);

答案 2 :(得分:2)
With Lodash:
var maps = {
"Recipe1" : ["Sugar", "Milk", "Bread"],
"Recipe2" : ["Rice", "Salt", "Carrots"]
};
var output = _.map(maps, function(value, key) {
return {name: key, ingredients: value};
});
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>