Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
}
like image 635
user320587 Avatar asked Feb 23 '26 02:02

user320587


2 Answers

This is pretty trivial to do without lodash, using Object.entries(), Array.prototype.map(), a destructured parameter, and shorthand property names for the returned object:

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

const output = Object.entries(maps).map(
  ([name, ingredients]) => ({ name, ingredients })
)

console.log(output)
like image 61
Patrick Roberts Avatar answered Feb 25 '26 15:02

Patrick Roberts


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>
like image 39
JellyRaptor Avatar answered Feb 25 '26 14:02

JellyRaptor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!