簡體   English   中英

通過鍵聚合對象數組

[英]Aggregate an array of objects by keys

我希望以一種更加用戶友好和聚合的方式輸出以下上下文數組。 我基本上想顯示按每個屬性分組的每種組合。 例如,對於以下上下文數組

const contexts = [
  { channel: 'email', preset: 'christmas', field: 'preamble bottom' },
  { channel: 'web', preset: 'christmas', field: 'preamble bottom' },
  { channel: 'email', preset: 'deal', field: 'preamble top' },
  { channel: 'email', preset: 'sale', field: 'preamble top' },
  { channel: 'web', preset: 'deal', field: 'preamble top' },
  { channel: 'web', preset: 'sale', field: 'preamble top' }
];

我想要以下回應

{
  'email, web':
    {
      'christmas': 'preamble bottom',
      'deal, sale': 'preamble top'
    }
}

我可以通過對頻道和預設進行分組來做到這一點,但我一直在努力尋求通用解決方案。 例如,上下文數組也可能看起來像這樣

const contexts = [
  { channel: 'email', preset: 'deal', field: 'vignette' },
  { channel: 'email', preset: 'deal', field: 'headline' },
  { channel: 'web', preset: 'deal', field: 'vignette' },
  { channel: 'web', preset: 'deal', field: 'headline' }
];

並應產生以下反應

{
  'email, web':
    {
      'deal': 'vignette, headline'
    }
}

有任何想法嗎? 感覺應該對此有一些優雅的解決方案。

您可以從field開始分組,然后進入channel 希望這可以幫助。

 const contexts = [ { channel: 'email', preset: 'christmas', field: 'preamble bottom' }, { channel: 'web', preset: 'christmas', field: 'preamble bottom' }, { channel: 'email', preset: 'deal', field: 'preamble top' }, { channel: 'email', preset: 'sale', field: 'preamble top' }, { channel: 'web', preset: 'deal', field: 'preamble top' }, { channel: 'web', preset: 'sale', field: 'preamble top' } ]; const contexts2 = [ { channel: 'email', preset: 'deal', field: 'vignette' }, { channel: 'email', preset: 'deal', field: 'headline' }, { channel: 'web', preset: 'deal', field: 'vignette' }, { channel: 'web', preset: 'deal', field: 'headline' } ]; const group = (arr) => { const byField = new Set(arr.map(({ field }) => field)); const byPreset = Array.from(byField).reduce((acc, val) => { const keys = new Set(arr.map(({ field, preset }) => field === val ? preset : null) .filter((item) => item)); const key = Array.from(keys).join(','); acc[key] = acc[key] ? `${acc[key]},${val}` : val; return acc; }, {}); return Object.keys(byPreset).reduce((acc, val) => { const fields = val.split(','); const keys = new Set(arr.filter(({ channel, preset }) => fields.some((item) => item === preset)) .map(({ channel }) => channel)); const key = Array.from(keys).join(','); acc[key] = { ...acc[key], [val]: byPreset[val] }; return acc; }, {}); }; console.log(group(contexts)); console.log(group(contexts2)); 

暫無
暫無

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

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