Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

use another arrays value in another array

I have an array (const second) which i’m using in select element, which shows numbers as dropdown {option.target}, my question: is there a way to check inside that map (which i’m using) if ‘target’ from ‘second’ array is equal to ‘id’ from ‘first’ array then drop down should show value of ‘name’ from first array and not numbers from ‘second’ array, so drop down should show kitchen, sauna …

should i have another map inside that map ?

codesandbox:
https://codesandbox.io/s/react-hook-form-array-fields-forked-x46672?file=/src/index.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

English is not my mother language so there could be mistakes.

>Solution :

It can be achieved using .find(), which returns the first element in an array that satisfies the provided testing function.

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>
  );
}

Live Example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading