简体   繁体   中英

Mapping from two different data sources

I have a React functional component with the following JSX:

import React from "react";

const Parent = () => {
  const arr1 = ["123", "456"];
  const arr2 = ["abc", "def"];

  return (
    <div>
      {arr1.map((item) => {
        return <div>{item}</div>;
      })}
      {arr2.map((item) => {
        return <div>{item}</div>;
      })}
    </div>
  );
};

export default Parent;

What I need this component to render is:

"123"
"abc"
"456"
"def"

Instead, it returns:

"123"
"456"
"abc"
"def"

I tried to get the result with a for loop, but for some reason it doesn't get triggered when the functional component is loaded, so I'm looking for a solution that involves .map() . Is there a way to get the needed result with .map() ?

Note: the lengths of arrays are always equal, hence the accepted answer.

Assuming that both array have the same length:

<div>
  {arr1.map((item, index) => (<>
    <div>{item}</div>
    <div>{arr2[index]}</div>
   </>);
  )}
</div>
return (
  <div>
    {arr1.map((value, index) => {
       return <> <div>{value}</div> <div>{arr2[index]}</div> </>
    })}
  </div>
);

Try this.

what you want to do is loop through both arrays at the same time, and store each value of both into a new array, something like the below.

I only added those length checks in case the arrays dont have the same size.

const Parent = () => {
  const arr1 = ["123", "456"];
  const arr2 = ["abc", "def"];

  let arr3 = [];

  if(arr1.length == arr2.length){
      for(let i =0;i<arr1.length;i++){
        arr3.push(arr1[i]);
        arr3.push(arr2[i]);    
      }
  }

  return (
    <div>
      {arr3.map((item) => {
        return <div>{item}</div>;
      })}
    </div>
  );
};

Some Resources:

There is no way you can use map alone: it preserves the structure of the source array, so you would get the same number of elements and it is not what you want, but you can use flatMap

arr1.flatMap((x, i) => [x, arr2[i]])

I would like to add that I don't think this is a problem you should solve with React: you would be depending on it too much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM