在Javascript中获取深层对象的所有键

前端之家收集整理的这篇文章主要介绍了在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

可能在插件的帮助下使用nodejs吗?

解决方法

您可以通过递归遍历对象来执行此操作:
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)将返回以下数组:

["1","2","3","4","5","5.test","5.tester","5.tester.name","count","counter","counter.count"]
原文链接:https://www.f2er.com/js/158854.html

猜你在找的JavaScript相关文章