Geo*_*lov 13 javascript node.js
我有以下对象:
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"
}
}
};
Run Code Online (Sandbox Code Playgroud)
我想检索以下结果:
可能在插件的帮助下使用nodejs吗?
Pet*_*son 19
您可以通过递归遍历对象来执行此操作:
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;
}
Run Code Online (Sandbox Code Playgroud)
getDeepKeys(abc)在问题中运行对象将返回以下数组:
["1", "2", "3", "4", "5", "5.test", "5.tester", "5.tester.name", "count", "counter", "counter.count"]
Run Code Online (Sandbox Code Playgroud)
小智 7
我知道这个帖子有点旧了...
此代码涵盖了 JSON 对象格式的所有条件,例如对象、对象数组、嵌套数组对象、带有数组对象的嵌套对象等。
getDeepKeys = function (obj) {
var keys = [];
for(var key in obj) {
if(typeof obj[key] === "object" && !Array.isArray(obj[key])) {
var subkeys = getDeepKeys(obj[key]);
keys = keys.concat(subkeys.map(function(subkey) {
return key + "." + subkey;
}));
} else if(Array.isArray(obj[key])) {
for(var i=0;i<obj[key].length;i++){
var subkeys = getDeepKeys(obj[key][i]);
keys = keys.concat(subkeys.map(function(subkey) {
return key + "[" + i + "]" + "." + subkey;
}));
}
} else {
keys.push(key);
}
}
return keys;
}
Run Code Online (Sandbox Code Playgroud)
较小的版本,没有副作用,函数体中只有 1 行:
function objectDeepKeys(obj){
return Object.keys(obj).filter(key => obj[key] instanceof Object).map(key => objectDeepKeys(obj[key]).map(k => `${key}.${k}`)).reduce((x, y) => x.concat(y), Object.keys(obj))
}
Run Code Online (Sandbox Code Playgroud)
function objectDeepKeys(obj){
return Object.keys(obj).filter(key => obj[key] instanceof Object).map(key => objectDeepKeys(obj[key]).map(k => `${key}.${k}`)).reduce((x, y) => x.concat(y), Object.keys(obj))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4488 次 |
| 最近记录: |