簡體   English   中英

通過利用 _.map 和 ._groupBy 用 lodash 重構數組

[英]Restructure an array with lodash by leveraging _.map and ._groupBy

我正在尋找用 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 },
    ],
  },
]

您可以使用flatMapgroupBy和映射鏈接整個操作。

 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>

可能有很多不同的方法可以做到這一點,但是,我發現最好的方法是:

  1. 將孩子們展平成一個陣列。
  2. 使用 _.groupBy 創建一個 map,這些條目鍵入名稱。
  3. 使用 _.entries 獲取 map 的鍵和值數組。
  4. 最后使用 _.map 將這些條目轉換為我們想要的 output。

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM