简体   繁体   中英

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.

  2. To retrieve the respective licenseTypes' subLicenses to be used in a subheading (or maybe body) depending on the view.

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

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
  • To map over the respective subLicenseTypes (Shallow Digger, Deep Digger, Poop shover, Grass shovler) to be used in the same cards subheading. 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

You can iterate the licenseType with Array.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"
    ]
  }
 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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