【发布时间】:2021-08-20 17:14:26
【问题描述】:
长话短说,我是一名初学者,正在尝试构建一个功能,以便我们接收用户对通过电子邮件发送的特定调查的反馈。
响应是一个对象数组和未定义的值。 每个对象都有 3 个属性:email、surveyId 和 choice。
我需要获得一个没有重复和未定义的新数组。
此外,用户只能为特定调查提供一个选择,因此我们不能有 2 个具有相同电子邮件和调查 ID 但选择不同的对象。 具有最低索引的 obj 将是第一个答案,这就是我们想要的。
例子:
const arr = [
{
email: 'mynewemail@gmail.com',
surveyId: '1234',
choice: 'no'
},
undefined,
{
email: 'mynewemail@gmail.com',
surveyId: '1234',
choice: 'yes'
},
{
email: 'example2@gmail.com',
surveyId: '1234',
choice: 'no'
},
undefined,
{
email: 'mynewemail@gmail.com',
surveyId: '4567',
choice: 'no'
},
{
email: 'mynewemail@gmail.com',
surveyId: '1234',
choice: 'yes'
},
{
email: 'example@gmail.com',
surveyId: '7689',
choice: 'yes'
}
];
我想要的结果:
filteredArray = [
{
email: 'mynewemail@gmail.com',
surveyId: '1234',
choice: 'no'
},
{
email: 'example2@gmail.com',
surveyId: '1234',
choice: 'no'
},
{
email: 'mynewemail@gmail.com',
surveyId: '4567',
choice: 'no'
},
{
email: 'example@gmail.com',
surveyId: '7689',
choice: 'yes'
}
];
所以删除未定义很容易:
const undefiniedFilteredArr = events.filter(e => e !== undefined);
我还可以过滤重复的对象,或者使用 lodash _uniqBy 甚至使用循环,我相信有很多方法可以做到这一点。
现在,我想不通的是如何过滤具有相同 email 和surveyId 但选择不同的对象,并选择索引最低的 obj。我不希望来自同一个电子邮件的两个不同反馈针对同一个调查 ID。
请注意,我可以添加一个名为 timestamp 的第四个属性,并使用它来确定选择的优先级,如果这样更容易的话。
提前感谢您的帮助。
另外,请注意我是初学者
【问题讨论】:
标签: javascript arrays filter javascript-objects