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

前端 未结 2 1868
清歌不尽
清歌不尽 2020-12-30 09:55

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 c         


        
相关标签:
2条回答
  • 2020-12-30 10:02

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

    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>
      );
    });
    
    0 讨论(0)
  • 2020-12-30 10:09

    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.

    0 讨论(0)
提交回复
热议问题