在Javascript中获取深层对象的所有键 [英] Get all keys of a deep object in Javascript

查看:322
本文介绍了在Javascript中获取深层对象的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象:

var abc = {
    1: "Raggruppamento a 1",
    2: "Raggruppamento a 2",
    3: "Raggruppamento a 3",
    4: "Raggruppamento a 4",
    count: '3',
    counter: {
        count: '3',
    },
    5: {
        test: "Raggruppamento a 1",

        tester: {
            name: "Ross"
        }
    }
};

我想检索以下结果:


  • abc [1]

  • abc [2]

  • abc [3]

  • abc [4]

  • abc.count

  • abc.counter.count

  • abc [5]

  • abc [5] .test

  • abc [5] .tester

  • abc [5] .tester.name

  • abc[1]
  • abc[2]
  • abc[3]
  • abc[4]
  • abc.count
  • abc.counter.count
  • abc[5]
  • abc[5].test
  • abc[5].tester
  • abc[5].tester.name

是否可以在插件的帮助下使用nodejs?

is that possible using nodejs maybe with the help of plugins?

推荐答案

您可以通过递归遍历对象来执行此操作:

You can do this by recursively traversing the object:

function getDeepKeys(obj) {
    var keys = [];
    for(var key in obj) {
        keys.push(key);
        if(typeof obj[key] === "object") {
            var subkeys = getDeepKeys(obj[key]);
            keys = keys.concat(subkeys.map(function(subkey) {
                return key + "." + subkey;
            }));
        }
    }
    return keys;
}

运行 getDeepKeys(abc)你问题中的对象将返回以下数组:

Running getDeepKeys(abc) on the object in your question will return the following array:

["1", "2", "3", "4", "5", "5.test", "5.tester", "5.tester.name", "count", "counter", "counter.count"]

这篇关于在Javascript中获取深层对象的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆