最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert keyvalue pairs to object using lodash - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

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./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);

发布评论

评论列表(0)

  1. 暂无评论