利用_.map和._groupBy来重组一个数组。

问题描述 投票:0回答:1

我想用 lodash 重组一个对象数组。

我一直在尝试调整网上找到的许多例子,但没有任何运气。看来我必须结合使用 _.map._groupBy 但我真的无法理解这个问题。

希望得到任何帮助

初始数组:

const entries = [
  {
    year: '2019',
    children: [
      { name: 'red', amount: 1, label: 'color' },
      { name: 'yellow', amount: 20, label: 'color' },
      { name: 'green', amount: 12, label: 'color' },
    ],
  },
  {
    year: '2020',
    children: [
      { name: 'red', amount: 1, label: 'color' },
      { name: 'yellow', amount: 3, label: 'color' },
    ],
  },
]

重组阵列:

[
  {
    id: 'red',
    data: [
      { year: '2019', amount: 1 },
      { year: '2020', amount: 1 },
    ],
  },
  {
    id: 'yellow',
    data: [
      { year: '2019', amount: 20 },
      { year: '2020', amount: 3 },
    ],
  },
  {
    id: 'green',
    data: [
      { year: '2019', amount: 12 },
    ],
  },
]
javascript arrays lodash
1个回答
2
投票

你可以将整个操作与 flatMap, groupBy 和映射。

const entries = [{ year: '2019', children: [{ name: 'red', amount: 1, label: 'color' }, { name: 'yellow', amount: 20, label: 'color' }, { name: 'green', amount: 12, label: 'color' }] }, { year: '2020', children: [{ name: 'red', amount: 1, label: 'color' }, { name: 'yellow', amount: 3, label: 'color' }] }],
    result = _(entries)
        .flatMap(({ year, children }) => _.map(children, ({ name: id, amount }) => ({ year, id, amount })))
        .groupBy('id')
        .map((data, id) => ({ id, data: _.map(data, ({ year, amount }) => ({ year, amount })) }))
        .value();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

0
投票

可能有不少不同的方法,但是,我发现最好的方法是。

  1. 把孩子们平铺到一个数组中
  2. 使用 _.groupBy 来创建一个以名字为键的这些条目的映射。
  3. 使用 _.entry 来获取映射的键和值的数组。
  4. 最后使用 _.map 将这些条目转化为我们想要的输出。

const entries = [
  {
    year: '2019',
    children: [
      { name: 'red', amount: 1, label: 'color' },
      { name: 'yellow', amount: 20, label: 'color' },
      { name: 'green', amount: 12, label: 'color' },
    ],
  },
  {
    year: '2020',
    children: [
      { name: 'red', amount: 1, label: 'color' },
      { name: 'yellow', amount: 3, label: 'color' },
    ],
  },
]

// Step 1
let flattenedChildren = _.flatMap(entries, e => e.children.map(c => { return { ...c, year: e.year } }));

// Step 2
let entryMap =  _.groupBy(flattenedChildren , "name");

// Step 3
let mapEntries = _.entries(entryMap);

// Step 4
let result = _.map(mapEntries , ([id, items]) => { return { id, data: items.map(item => _.pick(item, ["amount", "year"]))} });

console.log("Result:", result);
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> 
© www.soinside.com 2019 - 2024. All rights reserved.