简体   繁体   English

Angularjs:从json对象创建一个键数组

[英]Angularjs: Create an array of keys from json object

I have a json in the following structure: 我在以下结构中有一个json:

$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. 这仅适用于IE9 +,如果你的目标是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 正如@aduch所说,使用

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

Add the following code before making use of it to handle browsers that do not implement Object.keys 在使用它之前添加以下代码来处理不实现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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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