簡體   English   中英

鏈 lodash _.groupby() 與 reduce

[英]chain lodash _.groupby() with reduce

從一個類似這樣的數組開始:

const arr = [
  {id: "id_0", owner: "owner_0", state: "accepted"},
  {id: "id_1", owner: "owner_1", state: "denied"},
  {id: "id_2", owner: "owner_1", state: "accepted"},
  {id: "id_3", owner: "owner_1", state: "accepted"},
  {id: "id_4", owner: "owner_2", state: "pending"},
]

我需要按所有者對數據進行分組並格式化 ID。 id 必須是逗號分隔的字符串。 不需要返回狀態數據。

const formattedArr = {
  owner_0: {ids: "id_0"},
  owner_1: {ids: "id_1, id_2, id_3"}
  owner_2: {ids: "id_4"}
}

我一直在使用_.groupBy(arr, 'owner')但不確定如何使用回調或其他映射或減少來格式化 id 並將它們加入字符串。

與此類似,但最好使用最少的循環:

_.chain(arr)
  .groupBy('owner')
  .reduce(group => {
    //format the ids here
    return *formatted ids*
  }
  .value()

因此,在這種情況下,您實際上不需要 groupBy 。 減少可以輕松解決您的問題。

const result = arr.reduce((acc, { id, owner }) => {
  if (!acc[owner]) {
    acc[owner] = {ids: id};
    return acc;
  }

  acc[owner].ids += `, ${id}`;
  return acc;
}, {});

如果你更喜歡 lodash,它看起來幾乎一樣。

_.reduce(arr, (acc, { id, owner }) => {
  if (!acc[owner]) {
    acc[owner] = {ids: id};
    return acc;
  }

  acc[owner].ids += `, ${id}`;
  return acc;
}, {});

祝你好運。

這應該可以解決問題:

_.chain(arr)
  .groupBy('owner')
  .map(o => ({
     owner: o[0].owner,
     ids: o.reduce((acc, curr) => [...acc, curr.id], []).join(', ')
    }))
  .value();

JS 小提琴: https ://jsfiddle.net/z3mks4n6/

暫無
暫無

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

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