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

时间:2017-03-08 14:49:44

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

我想检索以下结果:

  • 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?

6 个答案:

答案 0 :(得分:17)

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

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

答案 1 :(得分:2)

考虑使用函数式风格实现 deepKeys。我们可以避免突变、变量重新分配、中间分配和其他副作用的头痛 -

  1. 如果输入 t 是一个对象,对于对象中的每个 (k,v) 对,将 k 附加到 path 并重复子问题,{{ 1}}
  2. (归纳)输入不是一个对象。返回格式化的 v

我们可以将其编码如下 -

path

实现这个程序的另一个很好的选择是 JavaScript 的生成器。请注意此 const deepKeys = (t, path = []) => Object(t) === t ? Object // 1 .entries(t) .flatMap(([k,v]) => deepKeys(v, [...path, k])) : [ path.join(".") ] // 2 const input = {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"}}} for (const path of deepKeys(input)) console.log(path) 与上述实现之间的相似性。他们都有效地做同样的事情 -

deepKeys

function* deepKeys (t, path = []) { switch(t?.constructor) { case Object: for (const [k,v] of Object.entries(t)) // 1 yield* deepKeys(v, [...path, k]) break default: yield path.join(".") // 2 } } const input = {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"}}} for (const path of deepKeys(input)) console.log(path) 的每个变体的输出相同 -

deepKeys

答案 2 :(得分:0)

我使用了这段代码(以前来自&#39; Peter Olson&#39;,使用lodash的代码的一些修补程序来获取密钥,并检查某些值是否为Date:< / p>

getDeepKeys = function (obj) {
  let keys = [];
  for (let key in Object.keys(obj)) {
    let value = obj[key];
    if (_.isDate(value)) {## Heading ##
      keys.push(key);
    } else if (_.isObject(value)) {
      let subkeys = getDeepKeys(value);
      keys = keys.concat(subkeys.map(function(subkey) {
        return key + "." + subkey;
      }));
    } else {
      keys.push(key)
    }
  }
  return keys;
}

我还检查了值mongoDBRef是否使用了这样的条件:((_.isObject(value)) && (value && value.oid))

答案 3 :(得分:0)

我知道这是旧文章...

此代码涵盖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;
}

答案 4 :(得分:0)

  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++){
              if ( typeof (obj[key][i]) == "string") {
                 console.log(obj[key][i])
                 keys.push(key)
              }
              else{
                   var subkeys = getDeepKeys(obj[key][i]);
             keys = keys.concat(subkeys.map(function(subkey) {
              return key + "[" + i + "]" + "." + subkey;
             }));
              }

          }
      } else {
        keys.push(key);
      }
  }
  return keys;

}

答案 5 :(得分:0)

使用递归函数会有帮助

Class Man {
  constructor(name) {
    this.name = name;
  }
  draw(context) { drawMan(context, this.name) };
}