简体   繁体   中英

Angularjs: Create an array of keys from json object

I have a json in the following structure:

$scope.hi=[{
"a":1,
"b":true,
"c":"great"
}];

I want to extract only the keys and make an array like

$scope.bye=["a","b","c"];

Though seems to be a very basic question but would be very helpful for me.

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.

您可以使用#aduch变体或开始使用名为underscorejs的优秀lib

_.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/keys
if (!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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM