6

so i have object that have many properties, i need to get all values and property names from that object, i'm not sure what is best and easiest way to do it. I already tried few methods but didn't had any luck with it

angular.forEach(array, function(value, key){
   console.log(value);
});
2
  • 2
    Duplicate of this question stackoverflow.com/questions/30147983/… Commented Dec 1, 2016 at 9:38
  • What is wrong with this approach? You have the key and the value Commented Dec 1, 2016 at 9:58

3 Answers 3

11

You can also use the Object.keys() which returns an array of the keys of the object. For instance :

var obj = { 0 : "a", 1 : "b", 2 : "c"};
console.log(Object.keys(obj)); // [0, 1, 2]

You can also use the Object.values() which returns an array of the values of an object :

var obj = { 0 : "a", 1 : "b", 2 : "c"};
console.log(Object.values(obj)); // ['a', 'b', 'c']
Sign up to request clarification or add additional context in comments.

Comments

7

forEach works with arrays, for object properties you need:

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        console.log(property, ' ', object[property]);
    }
}

1 Comment

You beat me on the time, this is the right way to go.
3

you can achive with two foreach in angular like below

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   
  </body>
<script>
  var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name =[
   {
     "Name": "myname",
     "Password": "mypasscode"
   },
   {
     "Name": "yourname",
     "Password": "yourcasscode"
   }
];
 angular.forEach($scope.name, function(k , v) {
        angular.forEach(k, function(x , y) {
            alert(y+"--"+x);
        })
    })
});
</script>
</html>

1 Comment

Thank you for answer, already got solution from Luis Sieira's answer.

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.