如何同时映射两个数组? [英] How can I map over two arrays at the same time?

查看:109
本文介绍了如何同时映射两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,一个是网址,另一个是内容。
他们看起来像这样:

I have two arrays, one with urls and one with content. They look like this:

const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ]
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]

如何同时映射两个数组并在新创建的元素中使用它们的值?

How can I map over both arrays at the same time and use their value in my newly created element?

我需要使用我的reactplayer的url值和内容的值作为播放器下面的文本。

I need to use the value of the url for my reactplayer and the the value of the content as the text underneath the player.

所以看起来应该是这样的:

So it should look something like this:

<Reactplayer url"link0" />
<ControlLabel>content0</ControlLabel>

这可能吗?什么是更好的设置方法?

Is this possible? And what would be a better way of setting this up?

推荐答案

使用 map 的第二个参数,这是索引当前元素,您可以访问第二个数组的正确元素。

Using the second parameter of map, which is the index of the current element, you can access the correct element of the second array.

const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ];
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]

const players = link.map((value, index) => {
  const linkContent = content[index];
  return (
    <div>
      <Reactplayer url="{value}" />
      <ControlLabel>{linkContent}</ControlLabel>
    </div>
  );
});






这是<$ c的完美候选者$ c> zip 各种库提供的方法,例如 Lodash Rambda ,如果您的项目中有其中一个。


This is the perfect candidate for the zip method which is available with various libraries, such as Lodash or Rambda, if you have one of those in your project.

const players = _.zip(link, content).map((value) => {
  return (
    <div>
      <Reactplayer url="{value[0]}" />
      <ControlLabel>{value[1]}</ControlLabel>
    </div>
  );
});

这篇关于如何同时映射两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆