使用lodash将键/值对转换为对象

时间:2018-05-17 19:17:38

标签: javascript lodash

我有一组键/值对,我想将它们转换为对象。使用lodash做到这一点的最佳方法是什么。

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

寻找下面的内容

{
  name: "Recipe1",
  ingredients: ["Sugar", "Milk", "Bread"]
},
{
  name: "Recipe2",
  ingredients: ["Rice", "Salt", "Carrots"]
}

3 个答案:

答案 0 :(得分:4)

如果没有lodash,使用Object.entries()Array.prototype.map()destructured parametershorthand 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获取nameingredients参数,并使用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>

相关问题