0

I'm having trouble accessing the values of a nested array and I've been stuck on it for days, hoping someone can help!

I've just started learning React and i'm working on an app that fetches the data from Wordpress using graphql and apollo

The array structure when I console my data:

{__typename: 'Yarn', name: 'Brick Red', yarnFields: {…}}
name: "Brick Red"
yarnFields:
yarnColor: "#cb4154"
yarnFiber: Array(1)
0: {__typename: 'Fiber', name: 'Merino'}
length: 1
[[Prototype]]: Array(0)
yarnPrice: 6.5
__typename: "Yarn_Yarnfields"
[[Prototype]]: Object
__typename: "Yarn"
[[Prototype]]: Object

The array structure from graphql:


{
  "data": {
    "yarns": {
      "nodes": [
        {
          "name": "Brick Red",
          "id": "dGVybToyNTI=",
          "yarnFields": {
            "yarnColor": "#cb4154",
            "yarnPrice": 6.5,
            "yarnFiber": [
              {
                "name": "Merino"
              }
            ]
          }
        },
        {
          "name": "Burgundy",
          "id": "dGVybToyNzg=",
          "yarnFields": {
            "yarnColor": "#662d40",
            "yarnPrice": 9.11,
            "yarnFiber": null
          }
        },
        {
          "name": "Cobalt Blue",
          "id": "dGVybToyOTQ=",
          "yarnFields": {
            "yarnColor": "#1664af",
            "yarnPrice": 7.54,
            "yarnFiber": null
          }
        },


etc

I can get all the other values by using this syntax:

{yarn?.yarnFields?.yarnPrice}

the value i need to get is yarnFiber.name ( in the case the value is "Merino")

but when i use the same syntax for yarnFiber it returns undefined

My JSX Code to map through the JSON object:

 const { loading, error, data } = useQuery(YARNS_QUERY);
 if (isEmpty ( data )){
      return null;
    }

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error :(</p>;
  
   return (
     <>


         {data.yarns.nodes.map((yarn, i) => (
              <DK key={i} yarn={yarn}/>
            
           ))} 

My Component where I display the yarn info:

 return (
        <div>
            <div onClick={change} 
                data-color={yarn?.name}
                data-price={yarn?.yarnFields?.yarnPrice}
                data-fiber={yarn?.yarnFields?.yarnFiber?.name}
               
                style={{
                    background:yarn?.yarnFields?.yarnColor, 
                    width: '50px', 
                    height: '50px', 
                //  border:'5px dashed #2d2e2e',
                    borderRadius: '50%'}}>
     fiber: {yarn.yarnFields?.yarnFiber?.name} // returns empty
            </div>
        </div>
    );

I've tried mapping through the nested array but i can't seem to get the syntax correct to fit my code. i'm not even sure if thats what i need to do!

Any help appreciated but would love the solution in detail as I'm a total noob!

UPDATE:

the yarnFiber array has multiple values that need to be displayed

"name": "Burgundy",
          "id": "dGVybToyNzg=",
          "yarnFields": {
            "yarnColor": "#662d40",
            "yarnPrice": 9.11,
            "yarnFiber": [
              {
                "name": "Merino Wool"
              },
              {
                "name": "Silk"
              },
              {
                "name": "Cashmere"
              }
            ]
          }
        },

how should i reflect this in my code?

thanks again

2
  • yarnFiber is an array. So yarnFiber[0].name. Commented Sep 3, 2022 at 12:50
  • Thank you Andy, I accepted Ipizzinidev's answer because it had the full code in the answer. After days of struggling with this, the less I had to think about it the better :) Commented Sep 3, 2022 at 16:20

1 Answer 1

0

yarnFiber is an array so you need to reference its objects by index:

fiber: {yarn.yarnFields?.yarnFiber && yarn.yarnFields?.yarnFiber.length > 0
  ? yarn.yarnFields?.yarnFiber[0].name
  : 'No fiber'
}

If you need to display all names in the array you can just map through them:

{
  yarn.yarnFields?.yarnFiber && yarn.yarnFields?.yarnFiber.length > 0
    ? yarn.yarnFields?.yarnFiber.map((fiber, index) => (
        <div key={index}>{fiber.name}</div>
      ))
    : 'No fibers';
}
Sign up to request clarification or add additional context in comments.

4 Comments

Would the code need to change if the array has multiple values to be displayed? I put the updated array result into my question for ease of reading
@user19910578 Yes, check edited answer
thank you. it returns [object Object],[object Object],[object Object], why is that?
UPDATE: I changed the code to {yarn.yarnFields?.yarnFiber && yarn.yarnFields?.yarnFiber.length > 0 ? yarn.yarnFields?.yarnFiber.map((fiber, index) => { // <p key={index}>{JSON.stringify(fiber.name)}</p> return fiber.name }) : 'No fibers' } after ready this answer from Konstantin.it works. stackoverflow.com/questions/38548134/…. Thanks again for your answer Ipizzinidev it got me out of a rough spot :)

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.