Home > Enterprise >  Accessing nested array in an object returning undefined
Accessing nested array in an object returning undefined

Time:09-04

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

CodePudding user response:

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'
}
  • Related