扩展数组而不是在AngularJS中替换(Extending array instead of replacing in AngularJS)

系统教程 行业动态 更新时间:2024-06-14 16:57:40
扩展数组而不是在AngularJS中替换(Extending array instead of replacing in AngularJS)

我有一个函数,用一个新的替换LocalStorage中的数组。 它看起来像这样:

$scope.extendData = function () { $scope.recordlist = $scope.filteredRecordsToExtend; jsonToRecordLocalStorage($scope.recordlist); };

我要做的是创建另一个函数,而不是用新数组(filteredRecordsToExtend)替换记录列表,它实际上将新数组中的对象添加到现有数组中,并附加它们。

我尝试了以下方法:

$scope.extendData = function () { $scope.recordlist.push($scope.filteredRecordsToExtend); jsonToRecordLocalStorage($scope.recordlist); };

但它创建了一个包含其中对象的新数组,它不会仅附加对象。

哦,我已经加载了LoDash,所以它可能有用吗?

有小费吗?

I have a function that replaces an array in LocalStorage with a new one. It looks like this:

$scope.extendData = function () { $scope.recordlist = $scope.filteredRecordsToExtend; jsonToRecordLocalStorage($scope.recordlist); };

What I'm trying to do is to create another function that instead of replacing recordlist with a new array (filteredRecordsToExtend), it actually adds the objects from the new array to the existing one, appending them.

I tried the following:

$scope.extendData = function () { $scope.recordlist.push($scope.filteredRecordsToExtend); jsonToRecordLocalStorage($scope.recordlist); };

But it creates a new array with the objects inside it, it doesn't append the only the objects.

Oh, and I've LoDash loaded, so maybe it could be of use?

Any tips?

最满意答案

您可以使用Lodash( .flatten() )“展平”嵌套数组,也可以使用.concat()而不是.push()来合并2个或更多数组。

Lodash:

$scope.recordlist = _.flatten($scope.recordlist.push($scope.filteredRecordsToExtend))

普通JS:

$scope.recordlist = $scope.recordlist.concat($scope.filteredRecordsToExtend)

You can either "flat" a nested array with Lodash (.flatten()) or you can use .concat(), instead of .push(), to merge 2 or more arrays.

Lodash:

$scope.recordlist = _.flatten($scope.recordlist.push($scope.filteredRecordsToExtend))

Plain JS:

$scope.recordlist = $scope.recordlist.concat($scope.filteredRecordsToExtend)

更多推荐

本文发布于:2023-04-13 12:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a346ce913cfa00e6ee2fe28a71def62e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   而不   数组   AngularJS   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!