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"]
}
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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With