簡體   English   中英

如何從包含嵌套對象的JavaScript對象文字中獲取所有屬性名稱?

[英]How can I get all the property names from a javascript object literal that contains nested objects?

例如,如果我有以下javascript對象文字:

var foo = {
    a: '1',
    b: {
        doit: function toit(){},
        c: true,
        d: {
          x: true,
          y: true
        }
    }
}

如何獲得所有屬性名稱的數組? 如:

['a', 'b', 'doit', 'c', 'd', 'x', 'y']

您可以使用此遞歸函數

function recursiveKeyFinder(object, result) {
    for (var key in object) {
        result.push(key);
        if (Object(object[key]).toString() === "[object Object]") {
            recursiveKeyFinder(object[key], result);
        }
    }
    return result;
}

console.log(recursiveKeyFinder(foo, []));
# [ 'a', 'b', 'doit', 'c', 'd', 'x', 'y' ]

您可以使用for in循環遍歷所有屬性,並將它們推入數組。

> 
for (var key in foo) {
   var obj = foo[key];
   for (var prop in obj) {
      // important check that this is objects own property 
      // not from prototype prop inherited
      if(obj.hasOwnProperty(prop)){
        arr.push(prop);
      }
   }
}

試試這個:(遞歸函數)

var foo = {
    a: '1',
    b: {
        doit: function toit(){},
        c: true,
        d: {
          x: true,
          y: true
        }
    }
};

var getKeys = function ( foo ) {
    var bar = [];

    for ( var key in foo ) {
        var _foo = foo [ key ];
        bar.push ( key );
        if ( typeof _foo === 'object') {
            var _bar = getKeys ( foo [key] );
            for (var _key in _bar ) {
                bar.push ( _bar[_key] );
            }

        }
    }

    return bar;
};


var bar = getKeys ( foo );

alert ( bar );

此處演示: JSFiddle

像這樣的函數可以完成任務:

function getKeysRecursive(obj)
{
  var keys = [];

  (function r(obj) {
    Object.keys(obj).forEach(function(key) {
      keys.push(key);
      if (obj[key] instanceof Object) {
        r(obj[key]);
      }
    });
  }(obj));

  return keys;
}

演示版

暫無
暫無

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

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