我有很多参加者,其中两人也是讲师。我想通过替换其中一位讲师来更新他/她,并将剩余的与会者完好无损地保留在数组中。
这是一个例子:
{
attendees: [
{ email: 'instructor1@gmail.com' },
{ email: 'instructor2@gmail.com' },
{ email: 'attendee@gmail.com' },
{ email: 'attendee1@gmail.com' },
{ email: 'attendee2@gmail.com' }
]
}
现在我提交了一组新的讲师,其中一位已更改:
{
instructors: [
{ email : 'test@gmail.com' },
{ email : 'instructor2@gmail.com' }
]
}
我的最终结果应该是:
{
attendees: [
{ email: 'test@gmail.com' },
{ email: 'instructor2@gmail.com' },
{ email: 'attendee@gmail.com' },
{ email: 'attendee1@gmail.com' },
{ email: 'attendee2@gmail.com' }
]
}
其中 test@gmail.com
已取代 instructor1@gmail.com
成为新讲师。我想我可以将 _.differenceBy 与 lodash 一起使用,但无法弄清楚如何替换数组中已更改的元素。有没有一种优雅的方法来做到这一点?
最佳答案
这里有一些解决方案,1) 将更新放入新变量或 2) 更新与会者变量。当然,这是相当有限的,因为您的数据没有类似于主键的东西(即:ID 字段)。如果您确实有主键,那么您可以修改这些示例来检查 id。
var attendees = [
{ email: 'instructor1@gmail.com' },
{ email: 'instructor2@gmail.com' },
{ email: 'attendee@gmail.com' },
{ email: 'attendee1@gmail.com' },
{ email: 'attendee2@gmail.com' }
]
var instructors = [
{ email : 'test@gmail.com' },
{ email : 'instructor2@gmail.com' }
]
// 1) in a new variable
var updatedAttendees = attendees.map(function(item, index) {
return instructors[index] || item;
})
// 2) In the same variable
for (var i = 0; i < attendees.length; i++) {
if (instructors[i]) {
attendees[i] = instructors[i];
}
}
如果您确实有主键,它可能看起来像这样。请注意,我们现在有两个嵌套循环。这个例子根本没有优化,只是为了给你一个总体思路:
var attendeesWithId = [
{ id: 1, email: 'instructor1@gmail.com' },
{ id: 2, email: 'instructor2@gmail.com' },
{ id: 3, email: 'attendee@gmail.com' },
{ id: 4, email: 'attendee1@gmail.com' },
{ id: 5, email: 'attendee2@gmail.com' }
]
var updates = [
{ id: 4, email: 'something-different@gmail.com' },
]
for (var j = 0; j < updates.length; j++) {
var update = updates[j];
for (var i = 0; i < attendeesWithId.length; i++) {
if (update.id === attendeesWithId[i].id) {
attendeesWithId[i] = update;
}
}
}
关于javascript - 替换数组中已更改的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36475648/