Loop through an array in React.js

  let allInfo = ['John', 'Doe']; 
    allInfo.map((name) => console.log("arr", name.firstName))

The statement above creates an array. I am looking to loop through the values and insert them into a new array for display in a dropdown menu.

    const info = [
        { value: "firstName", label: "firstName" },
        { value: "first",label: "first"},
        { value: "lastName", label: "lastName" }
    ]

I aim to iterate over the values of allInfo and assign them to the values in info. Instead of hardcoding value = "firstName", I want to fetch it from the allInfo array. Could someone assist me with this task?

Answer №1

To retrieve the info array, simply map the contents of the allInfo array.

const info = allInfo.map(name => ({
    value: name.firstName,
    label: name.firstName,
}));

If you wish to include some fixed values in the info array as well, utilize the spread operator like so:

const allInfoItems = allInfo.map(name => ({
    value: name.firstName,
    label: name.firstName,
}));

const info = [
    { value: 'something', label: 'something' },
    ...allInfoItems
]

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

Expression validation in AngularJS is a powerful tool for ensuring that

Attempting to implement input validation using an Angular expression because validation data will be sourced from the database. Attempting the following code: controller vm.key="ng-required" vm.value="true" html <input type="text" name="fi ...

Showing list data from script to template in vue - A step-by-step guide

My task involves displaying data from the main table in MySQL. I need to show the type of each major by comparing it with the id in the faculty table. I have successfully logged this information using console.log, but I'm unsure how to display it on t ...

Create a 3D rendering of an .obj file using Three.js without relying on the

I have a challenge of drawing a .obj file without loading it. Let's consider an example where the .obj file contains the following content: v 0.1 0.2 0.3 v 0.2 0.1 0.5 vt 0.5 -1.3 vn 0.7 0.0 0.7 f 1 2 3 By reading and parsing this file, I am able to ...

How can you determine if a specific variable exists within an array using an if statement?

Currently, I have designed a program that incorporates methods such as inputArray, selectionSort, binarySearch, and printArray. However, I am facing some difficulty while working on the main method. I need assistance in creating the main method that calls ...

ajax continues to repeatedly post old values

I am facing an issue with a form that auto submits and updates the page. Despite having a JavaScript function changing a button's value, AJAX is still posting the old value. AJAX $.ajax({ type: 'POST', url: this.act ...

What is the best way to link my React application with my Express API?

I've been immersed in my react app project for a while now, and I've recently delved into developing a server (using node and express) as well as planning to incorporate a database for it (MongoDB). My client-side react app has been smoothly run ...

How can one effectively overcome the constraint in HTML5 canvas that prevents altering the positions of previously sketched elements?

I am currently working on creating a wind map that displays data from seven different weather stations. My goal is to develop a fluid and interactive map similar to the ones found in this animation or this animation. In my research, I came across an artic ...

Implementing velocity.js for hover effects - a comprehensive guide

I'm seeking guidance on incorporating velocity.js for hover effects on elements. Currently, I utilize CSS for zooming in and out and animating elements upon user hover, while using velocity.js for initial page load animations. My query is: how shoul ...

Is the process of converting text to PNG and then reading it as a stream all completed on the front-end?

Is it feasible to achieve the following task? Allow the user to input text Generate a PNG from the entered text Upload the PNG to Pinata, in ReadStream format Perform all of these actions on the front-end Steps (1) and (2) have been successfully complete ...

Is this JavaScript code accurately matching the height of all three elements?

What I aim to achieve https://i.sstatic.net/aNCWV.png I attempted to create a condition-like statement: [ Comparing the heights of the 3 elements ] → When all are smaller than the height of content: Stretches to the full height of content. (jus ...

`Error encountered when attempting to convert date with Angular JS filter`

Utilizing angular js filter in the controller for date formatting. A user selects a date from a uib-datepicker-popup. The goal is to format this date using ISO 8601 (yyyy-mm-dd) date format. Upon logging the user-selected date, the output is as follows: S ...

Error retrieving user by provider account ID using Google and Firebase adapter with Next Auth

Encountering an issue while trying to integrate Google Provider with Firebase Adapter in Next Auth. Upon selecting an account, the following error is displayed: Running Firebase 9 TypeError: client.collection is not a function at getUserByProvider ...

What are some methods to avoid clipping absolute positioned elements while maintaining a box shadow around the parent div?

Here is an example to illustrate my question: Example Code The code provided above is a simplified version of my actual code. I am facing an issue where setting the wrap-div to overflow: visible prevents the menu from being cut off, but it also causes the ...

Using Vue.js as a view engine for ExpressJS

I'm on the hunt for a solution similar to React for ExpressJS, but tailored for Vue.js instead. Currently, I'm facing challenges when it comes to passing data from my database (mongoose) to my view. Right now, I'm utilizing the handlebars v ...

Hiding an image when pressing on a navbar icon: Tips and tricks

How can I toggle the visibility of an image when the bars icon is pressed on smaller screens, using CSS without JQuery or JavaScript? I have attempted to hide the image with visibility: hidden; in CSS but it does not work as intended. Please run this cod ...

What method can be used to keep Chromium open while using Puppeteer?

I am trying to figure out how to launch only one instance of Chromium from my first script and then connect to it from subsequent scripts. I am aware of the puppeteer.connect() method, but the issue is that when I start the script responsible for launching ...

Top method for stacking several divs in a vertical line

In search of the most effective method for organizing numerous dynamically generated divs (all with identical widths) in a vertical stack, two potential solutions have emerged: Utilize float:left... Implement an unordered list and enclose each div within ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

PHP split string into an array

Having an issue with PHP while trying to convert a string into an array. The problem is that there are unnecessary commas within the string which I don't want to split. This is the string in question: 123456,ABC1234,Realtor,123-123-1234,"United Sta ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...