我的代码有效。我只是好奇是否有更好的方法来做到这一点。例如,只有一两行。
ArtistDataService.update(entityData).then(function(response) {
var artist = response.data;
var artists = feedItem.event.artists;
var artistToUpdate = $filter('filter')(artists, {_id: artist._id});
var index = artists.indexOf(artistToUpdate[0]);
artists[index] = artist;
if (typeof feedItem.event.new === 'undefined') {
$state.go('feedItem.event.eventEdit');
} else {
$state.go('feedItem.event.eventNew');
}
});
最佳答案
一种更高效的方法(因为您要迭代两次,一次按 id 过滤以匹配,一次检索记录的索引)是简单地使用一个好的 ol'fashioned for in 循环。找到艺术家后,更新数组中的艺术家并中断。
for (var i in artists) {
if (artists[i]._id === artist._id) {
artists[i] = artist;
break;
}
}
关于javascript - 使用 Angularjs 是否有更新数组中对象的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33770795/