简体   繁体   English

遍历 javascript 中的嵌套对象数组

[英]iterating through nested array of objects in javascript

I have the following data that i need to iterate over.我有以下需要迭代的数据。

data structure数据结构

I have came up with the following raw solution to loop through and get my needed data, not sure if this is the most optimal way of doing so, is there any way to speed this up or just to improve the solution?我想出了以下原始解决方案来循环并获取我需要的数据,不确定这是否是这样做的最佳方式,有没有办法加快速度或只是改进解决方案?

 Object.entries(data[0]).forEach(([key, value]) => {
  for (const [key, test] of Object.entries(value)) {
    for (const [key, properties] of Object.entries(test.properties)) {
      for (const [keys, prop] of Object.entries(properties)) {
         console.log(prop);
      }
    }
    for (const [bestkeys, provisions] of Object.entries(test.provisions)) {
         //console.log(provisions);
    }
  }
});

If there is a specific pattern that you need to follow, then explicitly stating your pattern is usually the best way to go, especially for a less complex pattern such as this.如果您需要遵循特定的模式,那么明确说明您的模式通常是 go 的最佳方式,尤其是对于这种不太复杂的模式。 I re-wrote your example but using .values instead of .entries because you only used the values.我重写了您的示例,但使用.values而不是.entries因为您只使用了这些值。

Object.values(data[0]).forEach(val => {
  Object.values(val).forEach(test => {
    Object.values(test).forEach(property => {
      Object.values(property).forEach(prop => {
        console.log(prop);
      });
    });
    Object.values(test.provisions).forEach(provisions => {
      console.log(provisions);
    });
  });
});

However, if you only need to traverse all the branches and log all the deepest level of values, you could use recursive logic as well.但是,如果您只需要遍历所有分支并记录所有最深级别的值,您也可以使用递归逻辑。 ie IE

function logDeepestNestedValue(obj) {
  if (typeof obj === "object") {
    const values = Object.values(obj);
    values.forEach(logDeepestNestedValue);
  } else {
    console.log(obj);
  }
}
logDeepestNestedValues(data[0]);

Looking at your image I noticed that test.provisions might be an array and not an object, in which case you would not want to call Object.values on it, instead you can just use .forEach or directly a for of loop to log things there.查看您的图像,我注意到 test.provisions 可能是一个数组而不是 object,在这种情况下,您不想在其上调用Object.values ,而是可以只使用.forEach或直接使用for of循环来记录内容那里。

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

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