Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

node.js - Get all keys of a deep object in Javascript

I have the following object:

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: "Georgi"
        }
    }
};

I would like to retrieve the following result:

  • 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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...