0

Say I have an object like this

$scope.products = {
 blueDuck: {type:'duck', price: 5},
 redDuck: {type:'duck', price: 8},
 greenWolverine: {type:'wolverine', price:15}
}

I want to loop over the elements by type:

angular.forEach($scope.products, function(key, value) {
   console.log(value.type);
});

That would output:

duck
duck
wolverine

When I want to get a variable that's like:

duck
wolverine
0

2 Answers 2

1
 var items = []; //The temporary array to keep the values
 angular.forEach($scope.products, function(key,value) {
     if(items.indexOf(value) === -1) { //Check if the values is not already in the temp array
         items.push(key); //Push it to array
     }
 });
console.log(items); //Show the content of the array
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for suggestion. Added it.
0

you can store the variables coming from the loop inside an array, and check if the array contains your data from the loop. this is something i came up with

 var items = [];
 angular.forEach($scope.products, function(key,value) {
          if(items.indexOf(value) === -1) {
              items.push(key);
              console.log(value.type);
          }
      });

2 Comments

This will only print the values if they are repeated. console.log should be outside the loop in that case. See my answer
seriously you had to copy paste my code as an answer.you should have suggested an edit.

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.