简体   繁体   English

如何同时映射两个数组?

[英]How can I map over two arrays at the same time?

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? 如何同时映射两个数组并在新创建的元素中使用它们的值?

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. 我需要使用我的reactplayer的url值和内容的值作为播放器下面的文本。

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? 什么是更好的设置方法?

Using the second parameter of map , which is the index of the current element, you can access the correct element of the second array. 使用map的第二个参数(即当前元素的索引),可以访问第二个数组的正确元素。

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

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. 这是zip方法的完美候选 ,如果您的项目中有一个,可以使用各种库,例如LodashRambda

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

You would be better off having it as: 你最好把它当成:

const data = [
    { link: "www.test0.com", text: "this is test0 content" },
    { link: "www.test1.com", text: "this is test1 content" }
];

You would then render content like: 然后,您将呈现以下内容:

render() {
    var links = [];
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        links.push(<div><Reactplayer url={item.link}/><ControlLabel>{item.text}</ControlLabel></div>);
    }

    return (<div>{links}</div>);
}

Please note, this is untested code as I don't have a JSX project currently setup that I can test it in. 请注意,这是未经测试的代码,因为我目前没有安装可以测试它的JSX项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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