简体   繁体   English

如何遍历嵌套在对象内的数组,而对象又嵌套在数组中?

[英]How do I iterate through an array that is nested inside an object that is in turn nested in an array?

What I want to accomplish: 我要完成的工作:

  1. To retrieve all licenseTypes (digger and shovler) so that I can insert them in a header div. 检索所有licenseTypes(digger和shovler),以便可以将它们插入标头div中。

  2. To retrieve the respective licenseTypes' subLicenses to be used in a subheading (or maybe body) depending on the view. 根据视图检索要在子标题(或正文)中使用的各个licenseTypes的subLicense。

My array looks like this: 我的数组如下所示:

const licenseType = [
    {
      diggerLisense: [
        "Shallow Digger",
        "Deep Digger"
      ]
    },
      shoverlerLicense: [
        "Poop shovler",
        "Grass shovler"
      ]
    }
 ]

So basically, I have this structure: 所以基本上,我有这个结构:

licenseType > subLicenseType > subSubLicenseType licenseType> subLicenseType> subSubLicenseType

I specifically decided on this nested order for three reasons: 我专门决定此嵌套顺序的原因有以下三个:

  • To map over the licenseTypes (digger and shovler) so that it can be used in a card Heading 映射licenseTypes(挖掘程序和shovler),以便可以在卡标题中使用
  • To map over the respective subLicenseTypes (Shallow Digger, Deep Digger, Poop shover, Grass shovler) to be used in the same cards subheading. 映射要在同一副卡子标题中使用的各个subLicenseType(浅挖土机,深挖土机,便便堆放管,草堆放管)。 For some reason I think it's easier to handle state this way. 由于某种原因,我认为以这种方式处理状态会更容易。
  • To keep all license types in a neat object structure that can be exported/imported throughout my project. 为了使所有许可证类型都保持整洁的对象结构,可以在我的整个项目中进行导出/导入。

Any help or accusations is greatly appreciated here. 如有任何帮助或指责,在此表示感谢。 BTW, I have searched other questions and nothing exactly like the structure I have described here. 顺便说一句,我搜索了其他问题,但没有完全像我在这里描述的结构那样。

Edit: I want to thank the overwhelming and swift response that you've all offered. 编辑:我要感谢你们都提供的压倒性的迅速反应。 I'm amazed at how quickly you people help. 你们的帮助速度如此之快,让我感到惊讶。 This is my first question on here and I can't believe the speed of the response. 这是我在这里的第一个问题,我不敢相信响应的速度。

I am currently working the suggestions that were offered including the one that suggests a different format. 我目前正在处理所提供的建议,包括建议另一种格式的建议。 I will post a fiddle of the end result later when I'm done. 完成后,我将发布最终结果的小提琴。 Thanks all you members of the stackoverflow community 谢谢所有stackoverflow社区的成员

You can iterate the licenseType with Array.map() . 您可以遍历licenseTypeArray.map() For each object get the first entry , and return whatever you want to display: 对于每个对象,请获取第一个条目 ,然后返回要显示的内容:

 const licenseType = [{"diggerLisense":["Shallow Digger","Deep Digger"]},{"shoverlerLicense":["Poop shovler","Grass shovler"]}]; const result = licenseType.map((o) => { const [license, subLicenses] = Object.entries(o)[0]; return ` <h1>${license}</h1> <ul> ${subLicenses.map((s) => `<li>${s}</li>`).join('\\n')} </ul> `; }); demo.innerHTML = result.join('\\n'); 
 <div id="demo"></div> 

However, having a changing key in an object, complicates it needlessly. 但是,在对象中具有更改的密钥会使它不必要地复杂化。 I suggest a slightly different format: 我建议使用略有不同的格式:

{
    license: 'digger',
    sub: ['Shallow Digger', 'Deep Digger']
}

 const licenseType = [{ "license": "digger", "sub": ["Shallow Digger","Deep Digger"]},{ "license": "shoverler", sub: ["Poop shovler","Grass shovler"]}]; const result = licenseType.map(({ license, sub }) => ` <h1>${license}</h1> <ul> ${sub.map((s) => `<li>${s}</li>`).join('\\n')} </ul> `); demo.innerHTML = result.join('\\n'); 
 <div id="demo"></div> 

Try this: 尝试这个:

licenseType.forEach(element => {
    element[Object.keys(element)[0]].forEach(subTypes => {
         console.log(subTypes);
     })
});

Given your current data set, you can do something like this. 给定当前数据集,您可以执行以下操作。

However, it would be easier if your top level data structure was an object, not an array. 但是,如果您的顶层数据结构是对象而不是数组,会更容易。

 const licenseType = [ { diggerLisense: [ "Shallow Digger", "Deep Digger" ] }, { shoverlerLicense: [ "Poop shovler", "Grass shovler" ] } ]; const getLicenses = () => licenseType.map(license => Object.keys(license)[0]); const getData = (toFind) => licenseType.find(license => Object.keys(license)[0] === toFind); const getSubtypes = (license) => { const data = getData(license); if (data) { subTypes = data[license]; } return subTypes; }; console.log(getLicenses()); console.log(getSubtypes('shoverlerLicense')); 

LicenseType is an array So you can access the license type like licenseType[i] where it represents the element of the array. for sub license type use 

sublicensetype = [] 
for (i = 0; i < licenseType.length; i++) { 
    for ( var k in licenseType[i]) sublicenseType.push(k) 
}

Try it like this fiddle : 试试这个小提琴

licenseType.forEach(function (type) {
  console.log('type', type);
  Object.keys(type).forEach(function (typeKey) {
   console.log('typeKey',typeKey);
   console.log('typeValues',type[typeKey]);
  });    
});

Also, you have a syntax error in your initial array: 另外,初始数组中存在语法错误:

const licenseType = [
  {
    diggerLisense: [
      "Shallow Digger",
      "Deep Digger"
    ]
  },
  { //this bracket was missing
    shoverlerLicense: [
      "Poop shovler",
      "Grass shovler"
    ]
  }
 ]

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

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