Search code examples
javascriptlodash

Convert key/value pairs to object using lodash


I have a set of key/value pairs that I would like to convert them as object. What is the best possible way to do this using lodash.

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

Looking for an out to look like below

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

Solution

  • 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>