Angularjs: Create an array of keys from json object Angularjs: Create an array of keys from json object json json

Angularjs: Create an array of keys from json object


This is what you need

Object.keys($scope.hi[0]);

This only works in IE9+ if you target IE.

An alternative might be to do fetch them with a loop

var obj = $scope.hi[0],    array = [];for (key in obj) {   if (obj.hasOwnProperty(key)) {       array.push(key);   }}

Also note that the order of the keys may not be respected depending on the browser implementation.


You can use #aduch variant or start to use great lib that called underscorejs

_.keys($scope.hi) // result: ["a","b","c"]


Just as @aduch said, use

Object.keys($scope.hi[0]).

Add the following code before making use of it to handle browsers that do not implement Object.keys

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keysif (!Object.keys) {  Object.keys = (function () {    'use strict';    var hasOwnProperty = Object.prototype.hasOwnProperty,        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),        dontEnums = [          'toString',          'toLocaleString',          'valueOf',          'hasOwnProperty',          'isPrototypeOf',          'propertyIsEnumerable',          'constructor'        ],        dontEnumsLength = dontEnums.length;    return function (obj) {      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {        throw new TypeError('Object.keys called on non-object');      }      var result = [], prop, i;      for (prop in obj) {        if (hasOwnProperty.call(obj, prop)) {          result.push(prop);        }      }      if (hasDontEnumBug) {        for (i = 0; i < dontEnumsLength; i++) {          if (hasOwnProperty.call(obj, dontEnums[i])) {            result.push(dontEnums[i]);          }        }      }      return result;    };  }());}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys