簡體   English   中英

Angularjs:從json對象創建一個鍵數組

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

我在以下結構中有一個json:

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

我想只提取鍵並制作一個類似的數組

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

雖然似乎是一個非常基本的問題,但對我來說非常有幫助。

這就是你需要的

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

這僅適用於IE9 +,如果你的目標是IE。

另一種方法是使用循環來獲取它們

var obj = $scope.hi[0],
    array = [];

for (key in obj) {
   if (obj.hasOwnProperty(key)) {
       array.push(key);
   }
}

另請注意,根據瀏覽器的實現,可能無法遵守鍵的順序。

您可以使用#aduch變體或開始使用名為underscorejs的優秀lib

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

正如@aduch所說,使用

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

在使用它之前添加以下代碼來處理不實現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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM