What is the best way to retrieve information from an array of objects and store them in individual variables?

I'm struggling to extract the necessary information from the array below, which was received from the backend. I need to utilize these values as error messages but my attempts to map have been unsuccessful.

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

I want something like the example below, but I can't figure it out?

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

Edit:

The issue is that I'm unable to access the data using dot notation. I am working with React and errorArray is passed as a prop. While I can console.log(errorArray) and see the array with objects inside, attempting to use dot notation results in an error: Uncaught TypeError: Cannot read properties of null (reading 'candidate').

Do I need to iterate over the array or take a different approach? Any guidance would be greatly appreciated.

Answer №1

Assuming the server consistently provides data in the specified format, the code snippet below should be effective.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating GeoJson using JavaScript

Currently, I am retrieving a latitude/longitude array using Ajax $.ajax({ type: "POST", url: '../m/m_share.php', data: 'zone=' + zone, dataType: 'json', success: function(tab) { var i = 0; ...

Interoperability between C's tiny-aes-c library and Javascript's CryptoJS

Utilizing the implementation from tiny-aes-c, take a look at this C code snippet: int main(int argc, char const *argv[]) { uint8_t key[6] = { 's','e','c','r','e','t' }; uint8_t iv[16] = ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

Preventing page refresh when typing in a form input: Tips and tricks

I'm currently puzzled by a small issue. In my web application, I have a chat box that consists of an input[type='text'] field and a button. My goal is to send the message to the server and clear the input field whenever the user clicks the b ...

Having issues with InstaFeed (search) feature and jQuery Mobile

As a new developer, I am working on my first JQM site. However, I am facing an issue with my search input form where the instafeed photos do not show up until after a manual page refresh following submission. Despite numerous attempts, I cannot seem to res ...

Changing the text color of a selected text in HTML

I have a feature to change the color of selected text using Javascript. Here is the method I am currently using: function marking_text(replacrmenthtml){ try { if (window.getSelection) { sel = window.getSelection(); var ...

Tips for minimizing deep nesting of asynchronous functions in Node.js

I have a goal to create a webpage that showcases data fetched from a database. To achieve this, I've written functions to retrieve the necessary information from the DB using Node.js. Being relatively new to Node.js, my understanding is that to displa ...

Error in Leaflet: Uncaught TypeError: layer.addEventParent is not a function in the promise

Having trouble with Leaflet clusterGroup, encountering the following error: Leaflet error Uncaught (in promise) TypeError: layer.addEventParent is not a function const markerClusters = new MarkerClusterGroup(); const clusters = []; const markers = []; co ...

Should a checkbox be added prior to the hyperlink?

html tags <ul class="navmore"> <li><a href="link-1">Link 1</a></li> <li><a href="link-2">Link 2</a></li> </ul> Jquery Implementation in the footer $(".navmore li a").each(function(){ v ...

Sending data between Angular and Python using both strings and JSON formats

Seeking assistance with a Python script that sends events to a server. Here is the code snippet: LOGGER = logging.getLogger("send_event") POST_EVENT_URL = "http://localhost:3000/event/" def send(name, data): url = POST_EVENT_URL + name headers = {& ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

What is the best way to change a decimal [] array into a dynamic [] array?

Is there a way to convert an array of known type, such as decimal, to an array of dynamic in a more advanced manner? I am currently able to perform this conversion manually, but I am curious if there is a more sophisticated approach available. decimal[] ...

Array of charactes which is available at no cost

I am facing a challenge with freeing an array of pointers in my code. To illustrate my issue, I have prepared a simple example that may contain errors. int main() { char ** strings = malloc(2); strings[0] = malloc(sizeof(char)*4); strings[1] ...

The value of the scope variable remains constant even after selecting a file

After selecting a file, I attempted to change the scope value to the file path. This is an html file <input type="file" name="file" onchange="angular.element(this).scope().showFilePath(this)"> <div>{{filename}}</div> In the controller ...

Learn how to efficiently redirect users without losing any valuable data after they sign up using localStorage

I am currently facing an issue with my sign up form. Whenever a user creates an account, I use localStorage to save the form values. However, if the user is redirected to another page after hitting the submit button, only the last user's data is saved ...

Observing the Result of a Function within a Controller Using Ng-Repeat in a Directive

I'm struggling with making a custom directive watch the result of a function that's bound to the scope in the controller. Here is the HTML. I'm passing the key of the ng-repeat to the function in the controller in order to determine whether ...