Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get access to an array in an array from REST API

Hi I’m trying to display variants in two separate categories Color and Size, to do this I need to get data from the api, I can access "attributes", but I would like to be able to access 0 and 1 and map them, I have no idea how to do this.

{variants.length > 1 ? (
        
   variants.attributes.map(({ name, values }) => (
     <ProductOptions
     key={`key-${name}`}
       name={name}
        values={values}
       selectedOptions={selectedOptions}
      setOptions={setOptions}
     />
    ))
  ) : (
    <Fragment />
  )}

enter image description here

Thank you so much!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As i understand the output of Array with 6 elements where each of that 6 has attributes and attributes is yet another array and you want to loop through those attributes so you need 2 loops. One to loop through parent array and seconds inside the child.

variants.map((variant) => {
  variant.attributes.map((attribute) => {
     console.log('attribute: ', attribute);
     console.log('attribute id: ',attribute.id);
  });
});

p.s. you may use forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach but it has little difference in this case.

Also it seems like you working with ReactJS and building some JSX to put into rendered jsx. I would argue to form the array upfront and in final jsx just insert the rows, so your final jsx will be more readable, especially in cases of double loops or any more complex jsx.

const attributes = [];
variants.map((variant) => {
  variant.attributes.map((attribute) => {
     console.log('attribute: ', attribute);
     console.log('attribute id: ',attribute.id);
     attributes.push(<div key={attribute.id}>{attribute.id}</div>)
  });
});

// later 

return (
   <div>
    {attributes}
   </div>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading