2016-04-07 41 views
0

我有一个与会者阵列,其中2个也是导师。我想通过替换他/她来更新其中一名教员,并将剩余的参加者保留在阵列中。替换已更改的元素

下面是一个例子:

{ 
     attendees: [ 
     { email: '[email protected]' }, 
     { email: '[email protected]' }, 
     { email: '[email protected]' }, 
     { email: '[email protected]' }, 
     { email: '[email protected]' } 
     ] 
    } 

现在我提交教官的新数组与他们的一个改变:

{ 
     instructors: [ 
     { email : '[email protected]' }, 
     { email : '[email protected]' } 
     ] 
    } 

而我最终的结果应该是:

{ 
     attendees: [ 
     { email: '[email protected]' }, 
     { email: '[email protected]' }, 
     { email: '[email protected]' }, 
     { email: '[email protected]' }, 
     { email: '[email protected]' } 
     ] 
    } 

其中[email protected]已取代[email protected]作为新教师。我想我可以使用_.differenceBy与lodash,但不知道如何替换数组中的已更改的元素。有没有一个优雅的方式来做到这一点?

+0

'阵列#CONCAT(阵列)' – Rayon

+2

这并未似乎没有道理。在原始设置中,知道某事的唯一方法是指导员通过检查电子邮件。替换之后,无法知道“测试”是一位教练。那是你要的吗? – Sigfried

+0

没有意义 –

回答

1

以下是一些解决方案,可以1)将更新放入新变量或2)更新与会者变量。当然,这是相当有限的,因为你的数据没有类似于主键的东西(例如:ID字段)。如果你有一个主键,那么你可以修改这些例子来检查ID。

var attendees = [ 
    { email: '[email protected]' }, 
    { email: '[email protected]' }, 
    { email: '[email protected]' }, 
    { email: '[email protected]' }, 
    { email: '[email protected]' } 
] 

var instructors = [ 
    { email : '[email protected]' }, 
    { email : '[email protected]' } 
] 

// 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: '[email protected]' }, 
    { id: 2, email: '[email protected]' }, 
    { id: 3, email: '[email protected]' }, 
    { id: 4, email: '[email protected]' }, 
    { id: 5, email: '[email protected]' } 
] 

var updates = [ 
    { id: 4, email: '[email protected]' }, 
] 

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; 
     } 
    } 
} 
0

这是否帮助

var initialData = { 
 
     attendees: [ 
 
     { email: '[email protected]' }, 
 
     { email: '[email protected]' }, 
 
     { email: '[email protected]' }, 
 
     { email: '[email protected]' }, 
 
     { email: '[email protected]' } 
 
     ] 
 
    } 
 

 
var updateWithThis = { 
 
     instructors: [ 
 
     { email : '[email protected]' }, 
 
     { email : '[email protected]' } 
 
     ] 
 
    } 
 

 
for(var i=0; i< updateWithThis.instructors.length;i++){ 
 
    initialData.attendees[i] = updateWithThis.instructors[i]; 
 
} 
 

 
document.write(JSON.stringify(initialData));