1

I am having trouble extracting the required data from the below array. It is received from the backend and I want to use the values as error messages. I have tried to map but to no avail.

const errorArray = [
  {
    "candidate": {
      "phone_number": [
        "Enter a valid phone number."
      ]
    },
    "amount": [
      "Minimum amount £10"
    ]
  }
]

I would like something similar to the below but can't work out how?

const phone_number = "Enter a valid phone number."
const amount = "Minimum amount £10"

Edit:

My problem is that I can't access the data using dot notation. I am working with react and errorArray is being passed as a prop. I can console.log(errorArray) and see the array with the objects inside, but when I use dot notation I get the error: Uncaught TypeError: Cannot read properties of null (reading 'candidate').

Do I need to loop over the array or something similar? Any direction would be appreciated.

  • 4
    `const phone_number = errorArray[0].candidate.phone_number;` –  Aug 18 '22 at 13:53
  • It would be a lot better to have it as an object and not a bunch of variables. – epascarello Aug 18 '22 at 13:55
  • @laylaR, It seems like you have a very short distance to cover here. There's virtually nothing standing in your way between having the `errorArray` array and being able to access any object or property contained within. Looking at ChrisG's comment -- does that actually give you what you needed to know, or is your question something else? What part of this are you having trouble with? Can you describe more about what you problems you encountered when you said "I have tried to map but to no avail" (what did you try?) "can't work out how" (why not?) – Wyck Aug 18 '22 at 14:09
  • [Working with Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – mykaf Aug 18 '22 at 14:13
  • Duplicate: [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) –  Aug 18 '22 at 14:16
  • My problem is that I can't access the data using dot notation. I am working with react and errorArray is being passes as a prop. I can console.log(errorArray) and see the array, but when I use dot notation I get the error: Uncaught TypeError: Cannot read properties of null (reading 'candidate'). Do I need to loop over the array or something similar? Any direction would be appreciated. –  Aug 18 '22 at 14:53

1 Answers1

3

The code below should work if the server will always return data in that same format.

 const phone_number = errorArray[0]. candidate.phone_number[0];
    const amount = errorArray[0].amount[0];
Adriaan
  • 17,741
  • 7
  • 42
  • 75