简体   繁体   中英

How to map a mapped const in another const React.js

Ok so say I have 3 arrays like so:

import React from 'react';

const hello = ['hello', 'hi', 'sup'];
const bye = ['bye', 'goodbye', 'see ya'];
const names = ['john', 'bob', 'jill'];

Then let's say that I want to map each array like so:

const helloWorld = hello.map(helloCode => {
  return (
    <div>{helloCode}</div>
  );
});

const goodBye = bye.map(byeCode => {
  return (
    <div>{byeCode}</div>
  );
});

const allNames = names.map(nameCode => {
  return (
    <div>{nameCode}</div>
  );
});  

Now suppose that I want to take all three of those mapped functions and map them like so:

const all = [helloWorld, byeWorld, allNames];

const Everything = all.map(allCode => {
    return (
        <div>{allCode}</div>
    );
});  

How would I go about doing that because this way doesn't seem to work. I really just need answers in react. Anyways if anyone can help me figure this out it would be much appreciated. Thanks!

You can flatten the array like this

const all = [helloWorld, byeWorld, allNames];
const flattenedArray = [].concat.apply([], all)
// or use array destructuring
// const flattenedArray = [...helloWorld, ...byeWorld, ...allNames]
const Everything = flattenedArray.map(allCode => {
    return (
        <div>{allCode}</div>
    );
}); 

Your all is an array of arrays. To convert it to an array, spread the inner arrays

const all = [...helloWorld, ...byeWorld, ...allNames]; //all  is now an array

const Everything = all.map(allCode => {
    return (
        <div>{allCode}</div>
    );
}); 

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