Reputation: 3857
I'm learning about JS and TypeScript and I need to generate a separate React component for each of these items:
Say I have this object
var regions = {
NA: ["US", "ABC1"],
EU: ["GB", "LX", "IT"],
FE: ["JP", "DEF1"],
CN: ["CN"]
}
I'm trying to loop through and return a component for each key (NA/EU/FE/CN) and each item in the array (US, ABC1, etc.)
I can print out the values I want in a for loop:
for (let key in region) {
for (let item in region[key]) {
console.log("key: " + key + " item " + region[key][item]);
}
}
as a sanity test, but instead of doing this, I want each item to be mapped to a Component so that from the function, I can return an entire list of Components. Any recommended ways of doing this?
Upvotes: 0
Views: 75
Reputation: 2223
I'm not totally certain this is what you're trying to do, but you could use something like lodash's mapValues
function to iterate over your object, and then turn each item of each array into a new component.
Here's an example: https://codesandbox.io/s/ll5n988mwm
Upvotes: 0
Reputation: 7542
It's a little unclear exactly what you are looking for when you say "return a component", but I'll give it a go with what I think you are saying. To fit into your loop code you could do something like the following:
const regionComponents = [];
for (let key in regions) {
for (let item in regions[key]) {
regionComponents.push(<MyComponent region={regions[key][item]} />);
}
}
return regionComponents;
Or if you wanted to shorten it a little bit:
return regions.map(region => region.map(subRegion => <MyComponent region={subRegion} />));
(Obviously that will return a 2D array with components, but if you are simply then putting that within JSX elsewhere to render React will handle de-nesting for you).
If this isn't what you were looking for, leave a comment / edit your post to be a little clearer and I'll try my best to update my answer.
Upvotes: 1