我有一个函数,用一个新的替换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)更多推荐
发布评论