简体   繁体   English

遍历嵌套对象并将子键作为单独的数组返回

[英]Iterate through nested object and return child keys as separate array

I want to iterate through nested Object and I want to store the all the child keys as separate array and return it as a Object(parent key as key and child keys as value).我想遍历嵌套对象,我想将所有子键存储为单独的数组并将其作为对象返回(父键作为键,子键作为值)。

let a = {
  b: {
     f: {
       g: "hi",
       i: "wow"
      },
      e: "hello"
   },
c: {
   j: "ola"
  },
d: {
   k: ["bonjour","salam"]
  }
}

And I am expecting object like this.我期待这样的对象。

{
  a:[b,c,d],
  b:[f,e],
  f:[g,i],
  c:[j],
  d:[k]
}

I tried and got result to some extent.我尝试并在某种程度上得到了结果。

let res = {};
let keyVal;

var isObject1: any = val => {
if (typeof val === 'object' && val)
res[keyVal] = Object.keys(val);
}
function retrieveObj(obj1) {
for (const key in obj1) {
  const value1: any = obj1[key];
  keyVal = key;
  if (isObject1(value1))      
  retrieveObj(value1)
 }
}
res['a'] = Object.keys(a);
retrieveObj(a);

Below is the output which I got.下面是我得到的输出。

 {
  a: [ 'b', 'c', 'd' ], 
  b: [ 'f', 'e' ], 
  c: [ 'j' ], 
  d: [ 'k' ] 
 }

can any one help me to get complete output.任何人都可以帮助我获得完整的输出。 Thanks in advance提前致谢

You have a few problems with your code你的代码有一些问题

  1. your isObject1 check on whether something is an object or not, is not working correctly, because typeof [1,2,3] == 'object' will return true .您的isObject1检查某物是否为对象,无法正常工作,因为typeof [1,2,3] == 'object'将返回true You need an additional check for !Array.isArray(val)您需要额外检查!Array.isArray(val)

  2. You are handling only the first level.您只处理第一级。 You need a recursive call for nested objects.您需要对嵌套对象进行递归调用。

  3. Not sure what compare is in your context不确定在您的上下文中compare是什么

  4. You should not define keyval as a global variable.您不应将keyval定义为全局变量。 If you need to pass values from one scope to another, use parameters, not global variables.如果需要将值从一个作用域传递到另一个作用域,请使用参数,而不是全局变量。

The following should work以下应该工作

 let a = { b: { f: { g: "hi", i: "wow" }, e: "hello" }, c: { j: "ola" }, d: { k: ["bonjour","salam"] } } function getAllKeys(p, o, m) { if (!o || typeof o !== "object" || Array.isArray(o)) return m; m[p] = Object.keys(o); for (let k of m[p]) getAllKeys(k, o[k], m) return m; } let m = getAllKeys("a", a, {}) console.log(m)

How does it work它是如何工作的

The function getAllKeys accepts as parameters函数getAllKeys接受作为参数

  • p the name of the property to look at p要查看的属性的名称
  • o the value of the property to look at o要查看的财产价值
  • m the result object where all the arrays are merged into m所有数组合并到的结果对象

First, if the o which is passed in, is not a "real" object we just return because we don't need to do anything on arrays or primitive types.首先,如果传入的o不是“真正的” object我们只需返回,因为我们不需要对数组或原始类型执行任何操作。 As typeof [...] and typeof null also return 'object' we need the two additional checks ...由于typeof [...]typeof null也返回'object'我们需要两个额外的检查 ...

Next we add all keys of the current object o to the result object under a key of p (ie the name of the object we are currently looking at)接下来我们将当前对象o所有键添加到结果对象的一个​​键p (即我们当前正在查看的对象的名称)

And then we check all keys of o recursively.然后我们递归地检查o所有键。 Ie, we pass the key k and value o[k] togehter with the result object m recursively into getAllKeys .即,我们将键k和值o[k]与结果对象m递归地getAllKeysgetAllKeys

The final return m is just for convinience, so that we don't need to define the resultobject prior to the first call of getAllKeys .最后的return m只是为了方便起见,因此我们不需要在第一次调用 getAllKeys 之前定义结果getAllKeys Without this return m we would need to call this as follows如果没有这个return m我们需要按如下方式调用它

let m = {};
getAllKeys("a", a, m); 

I don't know what you would expect from an object like the following我不知道你对像下面这样的对象有什么期望

let a = {
  b: {
    c: {
      d: 3
    }
  },
  e: {
    c: {
      f: 4
    }
  }
}

The current approach will only return c: ['f'] .当前的方法只会返回c: ['f'] If you want c: ['d', 'f'] , you would need the following如果你想要c: ['d', 'f'] ,你需要以下内容

m[p] = [ ...(m[p] || []), ...Object.keys(o)];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM