最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get property name and value from array - Stack Overflow

programmeradmin3浏览0评论

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);
});

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);
});
Share Improve this question asked Dec 1, 2016 at 9:37 SahbazSahbaz 1,2724 gold badges19 silver badges42 bronze badges 2
  • 2 Duplicate of this question stackoverflow.com/questions/30147983/… – rrd Commented Dec 1, 2016 at 9:38
  • What is wrong with this approach? You have the key and the value – taguenizy Commented Dec 1, 2016 at 9:58
Add a comment  | 

3 Answers 3

Reset to default 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']

forEach works with arrays, for object properties you need:

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

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>

发布评论

评论列表(0)

  1. 暂无评论