使用lodash映射/变换对象的javascript数组

时间:2018-10-26 10:26:19

标签: javascript lodash

我有一个看起来像这样的对象数组:

[
     {
      "group": {
        "name": "Software Developers",
        "desc":"some desc"
      },
      "name": "devs 1", 
        "file": "f1.csv"
    },
    {
      "group": {
        "name": "Software Developers",
        "desc":"some desc"
      },
      "name": "devs 2", 
      "file": "f2.csv"
    },
    {
      "group": {
        "name": "Ceos",
        "desc":"some desc"
      },
      "name": "ceos 1", 
      "file": "f3.csv"
    },
    {
      "group": {
        "name": "Ceos",
        "desc":"some desc"
      },
      "name": "ceos 2", 
      "file": "f4.csv"
    }
]

使用lodash如何将该json数组转换为如下形式:

[
    {
      "group": {
        "name": "Software Developers",
    "desc":"some desc"
      },
    lists: [{ "name": "devs 1", "file": "f1.csv" }, { "name": "devs 2", "file": "f2.csv" }]
    },
    {
      "group": {
        "name": "Ceos",
    "desc":"some desc"
      },
    lists: [{ "name": "ceos 1", "file": "f3.csv" }, { "name": "ceos 2", "file": "f4.csv" }]
    }
]

我尝试了各种解决方案,但没有任何运气。

2 个答案:

答案 0 :(得分:0)

_.groupBy() group.name,然后_.map()到所需的结构:

const data = [{"group":{"name":"Software Developers","desc":"some desc"},"name":"devs 1","file":"f1.csv"},{"group":{"name":"Software Developers","desc":"some desc"},"name":"devs 2","file":"f2.csv"},{"group":{"name":"Ceos","desc":"some desc"},"name":"ceos 1","file":"f3.csv"},{"group":{"name":"Ceos","desc":"some desc"},"name":"ceos 2","file":"f4.csv"}];

const result = _.flow([
  (arr) => _.groupBy(arr, 'group.name'),
  (groups) => _.map(groups, (g) => ({
    ..._.head(g).group,
    lists: _.map(g, o => _.pick(o, ['name', 'file']))
  }))
])(data);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:0)

您还可以使用Object.entriesreducemap通过ES6来实现,而不用破折号:

const data = [{ "group": { "name": "Software Developers", "desc": "some desc" }, "name": "devs 1", "file": "f1.csv" }, { "group": { "name": "Software Developers", "desc": "some desc" }, "name": "devs 2", "file": "f2.csv" }, { "group": { "name": "Ceos", "desc": "some desc" }, "name": "ceos 1", "file": "f3.csv" }, { "group": { "name": "Ceos", "desc": "some desc" }, "name": "ceos 2", "file": "f4.csv" } ]

const result = Object.entries(data.reduce((r,c) => 
  (r[c.group.name] = [...r[c.group.name] || [], c], r), {}))
    .reduce((r,[k,v]) => (r.push({ group: v[0].group, lists: v.map(({name, file}) => 
      ({ name, file })) }), r), [])

console.log(result)