Reputation: 1367
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"]
}
Upvotes: 2
Views: 5550
Reputation: 755
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>
Upvotes: 3
Reputation: 51866
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)
Upvotes: 4
Reputation: 191976
You can use Object.entries()
to get an array of key/value pairs. Iterate the pairs array with Array.map()
. Use destructuring assignment to get the name
and ingredients
params, and create the result object withshorthand 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);
Upvotes: 3