Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript how to map over two arrays one object

I do have an object which is containing some field, three of them are arrays. And I would like to map over them in one go.

Let me show how I am doing it right now:

containerNames = this.state.fileContent.xContainers.map(xContainer => <Container containerName={xContainer} />);

containerNames.push(this.state.fileContent.yContainers.map(yContainer => <Container containerName={yContainer} />));

containerNames.push(this.state.fileContent.zContainers.map(zContainer => <Container containerName={zContainer} />));

For me it does seems like it could be made differently. With one lambda?

like image 327
Suule Avatar asked May 12 '26 07:05

Suule


1 Answers

The code in OP will make something like [1, 2, 3, [4, 5, 6], [7, 8, 9]], which I hope is not what you want. If you want [1, 2, 3, 4, 5, 6, 7, 8, 9], use this:

const containerNames = ["xContainers", "yContainers", "zContainers"].
    flatMap(field => this.state.fileContent[field].map(...));

If you want [[1, 2, 3], [4, 5, 6], [7, 8, 9]], then change the flatMap into map.

like image 99
Amadan Avatar answered May 13 '26 20:05

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!