我有以下对象:
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"]