1


I am using AngularJS and I have a problem as below:
I have created an Object whose properties are arrays. For example:

$scope.myObject = {
   import: [ object1, object2,...,objectN ],
   export: [ object1', object2',...,objectN' ],
   ...
}

Now I want to create a new array which concats all arrays from myObject properties so that I can display them in HTML view with ng-repeat.
This is my Plnk sample code: http://plnkr.co/edit/Ca8OX7kX8wV8JmRYJCzS?p=preview
Please help me. Thanks.

2 Answers 2

1

With underscore or lodash :

_.flatten(_.values($scope.myObject));

See fiddle

I've added also a plain JS (EcmaScript 5+) method :

$scope.myObjectJS = [];
Object.keys($scope.myObject).forEach(function(key) {
   $scope.myObjectJS = $scope.myObjectJS.concat($scope.myObject[key]);  
});

The fact that I use Object.keys(obj) instead of for (var key in obj) exempts us to check for hasOwnProperty.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but it seems just correct with simple array/objects. In my case, it still return a blank array. Maybe it concats too soon when my properties still not get the results back from server?
The plnkr you provided does not reflect the question. In the template, you are ng-repeating over a variable called array that does not even exist. Furthermore, I don't see any concat method of your data.
1

If I understand your question right this should work.

var newArr = [];
for(var key in $scope.myObject){
  newArr = newArr.concat($scope.myObject[key]);
}

2 Comments

Need to assign result of concat() back into newArr.
Thanks but it returns the blank array. I have created Plnk to show my sample code: plnkr.co/edit/Ca8OX7kX8wV8JmRYJCzS?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.