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"]
}
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"]
}
Share
Improve this question
asked May 17, 2018 at 19:17
user320587user320587
1,3678 gold badges30 silver badges59 bronze badges
2
-
For the output, did you mean
maps: [ { name: ..., ingredients: ... }, { name: ..., ingredients: ... } ]
? – Patrick Roberts Commented May 17, 2018 at 19:20 -
const result = Object.keys(maps).map(k => ({name: k, ingredients: maps[k]}));
– Ele Commented May 17, 2018 at 19:24
3 Answers
Reset to default 4This 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./ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
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);