Lodash按多个键分组

时间:2019-05-16 15:02:55

标签: lodash

我有以下对象

[{ Venue: 'NY',
    Title: 'NY Feast',
    PromoDate: '5/1/18',
    EndDate: '5/1/18',
    Price : $49.99,
    Notes: '',
    'Image Assigned': '',
    'Image Ready': '',
    'Ad Scheduled': '' },
  { Venue: 'NY',
    Title: 'NY Flash',
    PromoDate: '5/1/18',
    EndDate: '5/1/18',
    Price : $40.99,
    Notes: '',
    'Image Assigned': '',
    'Image Ready': '',
    'Ad Scheduled': '' },
  { Venue: 'BOSTON',
    Title: 'Never Too Late',
    PromoDate: '5/1/18',
    EndDate: '5/1/18',
    Price : $9.99,
    Notes: '',
    'Image Assigned': '',
    'Image Ready': '',
    'Ad Scheduled': '' },
  { Venue: 'BOSTON',
    Title: 'The Reluctant Bride',
    PromoDate: '5/1/18',
    EndDate: '5/1/18',
    Price : $19.99,
    Notes: '',
    'Image Assigned': '',
    'Image Ready': '',
    'Ad Scheduled': '' 
 }
]

执行操作后的预期输出是

[{ Venue: 'NY',
    Titles:  [{Title: 'NY Feast', Price: '49.99'}, {Title:'NY Flash', Price: '$40.99'}],
    PromoDate: '5/1/18',
    EndDate: '5/1/18',
    Notes: '',
    'Image Assigned': '',
    'Image Ready': '',
    'Ad Scheduled': '' },
  { Venue: 'BOSTON',
    Titles: [{Title: 'Never Too Late', Price: '$9.99'}, {Title: 'The Reluctant Bride', Price: '$19.99'}] ,
    PromoDate: '5/1/18',
    EndDate: '5/1/18',
    Notes: '',
    'Image Assigned': '',
    'Image Ready': '',
    'Ad Scheduled': '' }
]

我正在与Lodash groupby尝试,但是它对我不起作用。我必须按标题,PromoDate和EndDate分组,因为它们是唯一字段。

我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用单个Array.reduce而不使用lodash来做到这一点:

let data = [{ Venue: 'NY', Title: 'NY Feast', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$49.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' }, { Venue: 'NY', Title: 'NY Flash', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$40.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' }, { Venue: 'BOSTON', Title: 'Never Too Late', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$9.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' }, { Venue: 'BOSTON', Title: 'The Reluctant Bride', PromoDate: '5/1/18', EndDate: '5/1/18', Price: '$19.99', Notes: '', 'Image Assigned': '', 'Image Ready': '', 'Ad Scheduled': '' } ]

let result = data.reduce((r, c) => {
  let key = `${c.Venue}-${c.PromoDate}-${c.EndDate}`
  let { Title, Price, ...other } = c
  r[key] = r[key] || { Titles: [], ...other }
  r[key].Titles.push({ Title, Price })
  return r
}, {})

console.log(Object.values(result))

这个想法是对组合键进行分组,然后简化为所需的属性。