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

Retrieving the previous value using JQuery's onChange event

Is there a way to retrieve the initial quantity value before it is changed with the onChange function in this code snippet? I'm encountering issues with the CSS while using this setup for an input box. You can view the problematic CSS here. Updating ...

BorderWoocommerce

Something odd has appeared around my shopping cart total ("WARENKORB SUMME") today. Could you please take a look at the screenshot below? Any idea how to remove it? This is for a Wordpress/WooCommerce store. I haven't made any recent changes - I su ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

Issue with Express.js and EJS application: The edit form fails to display the current category of the post

I've been developing a blogging application using Express, EJS, and MongoDB. You can check out the GitHub repository by clicking on the link. Within my application, I have separate collections for Posts and Post Categories. One issue I'm encoun ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

The router.push function does not properly redirect to the specified path; instead, it just reloads the current page

I am a newcomer to NextJS and facing a challenge where I need to transfer data from the current page to another page. However, instead of loading the defined path in router.push as pathname: "/booking/checkout/", it loads the current page. I wan ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

Static response is the way to go! Asynchronous responses just don't cut it

Currently in the process of developing an angular directive for displaying real-time charts. Below is the code snippet that encompasses everything, including link: function() { }, within the directive. Here's the code for a static directive that func ...

What is the reason behind TypeScript enclosing a class within an IIFE (Immediately Invoked Function

Behold the mighty TypeScript class: class Saluter { public static what(): string { return "Greater"; } public target: string; constructor(target: string) { this.target = target; } public salute(): string { ...

Scraping data from a website using Python by targeting the `<td

Just starting out with Python and Web Scraping... I'm trying to extract the numbers 1.16, 7.50, and 14.67 from the highlighted portion of code using td, class, table-matches__odds pageSoup.find_all, but so far haven't had any luck. Anyone have an ...

React-profiler: element type is not recognized as valid

After reading the React Docs and this informative medium article, I decided to experiment with the React profiler by implementing a simple example in my code. import React, { unstable_Profiler as Profiler } from 'react'; import logo from ' ...

I attempted to host my MERN stack application on a shared hosting platform, but encountered the error message stating "Unable to obtain lock for the application."

I am attempting to deploy a MERN stack application on shared hosting, but I encounter an error message when trying to run NPM INSTALL or stop my app. The error reads "Can't acquire lock for an app." https://i.stack.imgur.com/52g3n.png ...

What is the best way to align a series of divs vertically within columns?

Struggling to find the right words to ask this question has made it difficult for me to locate relevant search results. However, I believe a picture is worth a thousand words so...https://i.stack.imgur.com/LfPMO.png I am looking to create multiple columns ...

The challenge with using prepared statements in PHP/MySQL for inserting data into a form

Recently, I encountered an issue with the code below that takes information from a form and sends it to MySQL. Previously, everything was working fine for category, contents, date, and user ID fields. However, after adding a new column called 'secleve ...

Adjust the loading bar component in Material UI to allow for customizable color changes

I am currently learning how to use material ui. My goal is to customize the loading bar's CSS. I checked the documentation and utilized colorPrimary classes. However, the changes are not appearing as expected. Could you please guide me on how to resol ...

Generating HTML table rows dynamically from objects using Angular's ng-repeat functionality

In my Node-RED setup, I am utilizing the HTML angular code within a "template" node. Within my system, I have an object that consists of circuit boards distinguished by serial numbers. Each circuit board is equipped with two channels, each having its own ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Saving iFrame as Image using Codemirror and html2canvas

Here are a few experiments I conducted with html2canvas: Fiddle 1 (Using html2canvas): Fiddle 2 (Using html2canvas without Codemirror): Fiddle 3 (Using html2canvas with Codemirror): Fiddle 4 (Using html2canvas with Codemirror): I recently wante ...

Is it possible to include parameters in an HTML GET request with Electron.Net?

I have successfully implemented a function in an Angular component within an Electron application using HttpClient: var auth = "Bearer" + "abdedede"; let header = new HttpHeaders({ "Content-Type": 'application/json&a ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...