使用Angularjs有更新数组中对象的最佳实践吗?

时间:2015-11-18 02:26:49

标签: javascript angularjs

我的代码有效。我只是好奇是否有更好的方法来做到这一点。例如,只有一行或两行。

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');
    }
});

1 个答案:

答案 0 :(得分:2)

一种更高效的方式(因为你重复两次,一次用id过滤到一个匹配,一次用来检索记录的索引)就是简单地使用一个好的方法。循环塑造。找到艺术家后,更新数组中的艺术家并中断。

for (var i in artists) {
    if (artists[i]._id === artist._id) {
        artists[i] = artist;
        break; 
    }
}