环并通过值数组和组对象地图

塞尔达尔·穆斯塔法

我想小组活动中由创建创建它们,但保持与不同的JS数组方法兜兜转转销售人员我的数据。

我已筛选我的主要数据集中返回那些有销售人员的用户角色。

我有我的运动数据显示谁创造了活动

我现在已经将它们分组按销售人员。

在我的脑海中,我将其视为通过活动数组中的每个活动对象的循环/映射,检查 createdBy 名称并返回一个新的对象数组,这些对象具有按 createdBy 名称的结果组。

在我的脑海响起了方便,但围绕它不能得到。

我已经把下面:

  const filtered = usersData.filter((val) => val.role === 'sales');
// this returns only the sales people out of all the possible user roles in the following format: 
 
active: true
createdAt: "2019-04-11T21:00:00.000Z"
email: "[email protected]"
name: "Alexander Tom Jones"
phone: 3044283743
role: "sales"
_id: "5c8a20d32f8fb814b56fa187"

// my campaign data contains the name of the sales person:

budget: 57154564
company: "sales company"
createdAt: "2020-07-30T09:03:51.925Z"
createdBy: "sales user"
creator_id: "5f228c8d58769fc7d556a6fa"
endDate: "2020-11-08T00:00:00.000Z"
isDeleted: false
location: "Helsinki"
name: "sales test campaign"


// with this function I can return all of the campaigns created by a sales person 1 by 1:

const filteredCampaigns = campaignData.filter(
    (val) => val.createdBy === 'sales user'
  );

我只是无法弄清楚如何“循环”,通过每个销售人员。

我看过的map / reduce和GROUPBY解决方案,但没有一样是远程关闭。我哪里错了?

贾里德·史密斯

对于由属性分组,您通常需要使用Array.prototype.reduce在像这样的模式:

const bySalesPerson = campaignData.reduce((records, record) => {
  // get the property to group by, replace with the
  // actual property name you want (createdBy?)
  const { salesPerson } = record;

  // check if it exists in our accumulator object, if not
  // assign empty array
  if (!(salesPerson in records)) records[salesPerson] = [];

  // push current record into the array associated with
  // that value of the property, in this case a particular
  // sales person
  records[salesPerson].push(record);

  // return the accumulator object from the callback
  return records; 
}, {});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章