Reputation: 1272
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);
});
Upvotes: 6
Views: 17128
Reputation: 8280
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']
Upvotes: 11
Reputation: 31522
forEach works with arrays, for object properties you need:
for (var property in object) {
if (object.hasOwnProperty(property)) {
console.log(property, ' ', object[property]);
}
}
Upvotes: 7
Reputation: 2075
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>
Upvotes: 3