Home > other >  Get access to an array in an array from REST API
Get access to an array in an array from REST API

Time:02-03

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!

CodePudding user response:

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>
)
  •  Tags:  
  • Related