employ the value of one array in a different array

Currently, I am working with an array (const second) that is being used in a select element to display numbers as dropdown options {option.target}. My question is: Is there a way to check within this map (that I'm using) if the 'target' from the 'second' array matches the 'id' from the 'first' array? If they match, then the dropdown should display the value of 'name' from the first array instead of the numbers from the 'second' array. Therefore, the dropdown should show options like kitchen, sauna...

Do I need to include another map within this map?

For code examples and sandbox demonstration visit: here

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const first = [
    { id: 0, mode: "camera", name: "Home" },
    { id: 1, mode: "room", name: "Kitchen" },
    { id: 2, mode: "room", name: "Sauna" }
  ];

  const second = [
    { id: 0, source: 0, target: 1 },
    { id: 1, source: 0, target: 2 }
  ];

  return (
    <div>
      <select>
        {second?.map((option) => (
          <option>{option.target}</option>
        ))}{" "}
      </select>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I apologize for any language mistakes, English is not my native tongue.

Answer №1

To accomplish this, you can utilize the .find() method. This method returns the first element in an array that meets the specified criteria.

function App() {
  const first = [
    { id: 0, mode: "camera", name: "Camera" },
    { id: 1, mode: "room", name: "Kitchen" },
    { id: 2, mode: "room", name: "Sauna" }
  ];

  const second = [
    { id: 0, source: 0, target: 1 },
    { id: 1, source: 0, target: 2 }
  ];

  return (
    <div>
      <select>
        {second?.map((option) => (
          <option>{first.find(({id}) => id === option.target).name}</option>
        ))}{" "}
      </select>
    </div>
  );
}

View Live Example

Answer №2

To achieve the desired result, you can utilize a combination of the .map and .filter functions

const first = [
    { id: 0, mode: "camera", name: "Home" },
    { id: 1, mode: "room", name: "Kitchen" },
    { id: 2, mode: "room", name: "Sauna" }
  ];

  const second = [
    { id: 0, source: 0, target: 1 },
    { id: 1, source: 0, target: 2 }
  ];
  
  const keyToExtract = 'name';
  
  const values = second.map(value => {
   return first.filter(elem => elem.id === value.target)[0][keyToExtract]
  })

  console.log(values);

Answer №3

To access the other arrays member in your map, you can simply use the value via index or even better through Array.find() or Array.findIndex() method. Here's an example:

  return (
    <div>
      <select>
        {second?.map((option) => {
          const testee = first.find((el) => el.id === option.target);

          return testee === undefined ? (
            <option>{option.target}</option>
          ) : (
            <option>{testee.name}</option>
          );
        })}
      </select>
    </div>
  );

Check out the modified version of this code here: https://codesandbox.io/s/react-hook-form-array-fields-forked-vu2bfx

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

Loop stops after completing one iteration

I am currently working on a program that automatically generates ASCII text based on input numbers. Essentially, when a number is provided as input to the function, it will be displayed as magnified ASCII text. For example, an input of 0123456789 would gen ...

Send a callback function from the main component to a nested component in React

TASK: Implement a callback function in the parent component to toggle the sidebar in the child component. The following code snippet shows how to open the sidebar: <Sidebar show={status} /> <button onClick={() => setStatus((status) => !s ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

Displaying a clock using PHP

Seeking a way to display server time on my website, I have successfully implemented client-side time using JavaScript. How can I now showcase the server time? Are there any ZendFramework classes that can assist with this? Currently, I am utilizing the fo ...

What is the best way to divide multiple event handlers in jQuery?

Is there a way to organize the code below more effectively by splitting the multiple events into separate lines? $document.find('body').on( 'click dblclick mousedown mousemove mouseout mouseover mouseup mousewheel keydown keypress keyup ...

Extending a universal design concept to a new theme within the MUI (Material UI) framework

I have implemented MUI's ThemeProvider and set up a Themes.js file. Within this file, I have defined the globalTheme for managing global styles such as typography and border-radius. My intention is to extend the properties of globalTheme to both light ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

How can str_replace be used in an array?

Is it possible to use an str_replace function within an array? I have a script that retrieves values from a CSV file and inserts them into a MySQL database. However, some cells in the CSV file may contain '-', which signifies no value. The curren ...

The container holding the inner elements is slightly oversized by a couple of pixels

Check out this Plunker example. Hello everyone, I am currently working on fitting two inner divs (a title bar and a canvas) inside an outer div. These inner divs are generated dynamically and have specific fixed dimensions. Below is a sample code snippet ...

Ensuring all Bootstrap columns have equal height to match the tallest one

I have several .col-md-2 elements on my Bootstrap website, each containing an image of varying height. I am looking to ensure that all the columns have the same height so that I can align the images horizontally. Below is the HTML code: <div class="r ...

Obtain the DOM element for the Card Body in order to enable scrolling downwards

Currently utilizing ant.design and seeking to scroll the content of a <Card>'s body to the bottom. Two common solutions are available for achieving this. Insert an empty <div> at the bottom of the body and execute div.scrollIntoView() Ret ...

It appears that Javascript variables are behaving in a static manner

I am currently building a PHP website with a registration page for users. I am implementing the LOOPJ jQuery Autocomplete script from to enable users to select their country easily. In this process, I encountered an issue where the value of another field ...

Harvesting data from an HTML document using BeautifulSoup and Python

I am currently working on extracting text from an HTML file. The HTML file has the following structure: <li class="toclevel-1 tocsection-1"> <a href="#Baden-Württemberg"><span class="tocnumber">1</span> <span class= ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

JavaScript code that displays items in a shopping cart

I've set up the HTML and JS functionality for the cart, but I'm facing an issue where the JS doesn't render the cart items when the shop item is clicked. The styling in my HTML is done using Tailwind. If anyone could provide some assistance ...

What is the best way to ensure that the size and maximum length of a text input box are properly aligned?

Is there a way to ensure that the size and maxlength attributes of a text input box align correctly? It can be frustrating when these attributes don't match up due to font differences. Example Input: <input type="text" size="4" maxlength="4" /> ...

What is the best way to obtain the current route name within a Component?

Is it possible to retrieve the current route name in a controller? I have attempted using this.route, this.currentRoute, and this._routerRoot, but none of them seem to work. computed: { currentRoute:{ get(){ console.log(this.__routerRoo ...

Traversing a two-dimensional array backwards in JavaScript

I am working with an array that contains different teams: The structure looks like this: leagues = new Array( Array('Juventus'), Array('Milan'), Array('Inter')); My goal is to iterate through the array and generat ...

Is it possible to access a comprehensive list of all the elements that are currently available?

Is there a way to retrieve all HTML tag names that are supported by the browser for my web application? I want it to be displayed like this: console.log(getAllElements()) //[a, abbr, acronym, address, applet, area, base, ...] ...

The selected value does not appear in the react material-ui dropdown menu item

Here is the URL to access the React select menu item code on codesandbox: React select menu item. I am currently wrapping the menu item with a div and trying to change the values of the select drop down, but unfortunately the values are not populating in ...