0

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!

2
  • Can you add a sample of what array you want in output? Commented Feb 3, 2022 at 8:28
  • If you found my answer helpful please consider marking it as accepted :) Thanks Commented Feb 3, 2022 at 8:44

1 Answer 1

2

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>
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.