Home > database >  How do i extract data from an array of objects and assign to variables?
How do i extract data from an array of objects and assign to variables?

Time:08-18

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.

CodePudding user response:

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];

CodePudding user response:

you can try accessing individually like below

const phone_number = errorArray[0]. candidate.phone_number[0];
const amount = errorArray[0].amount[0];

or you can use javascript Destructuring as well

const {candidate: { phone_number } , amount} = errorArray[0]
console.log(phone_number[0], amount[0])
  • Related