I’ am trying store my data in array of objects and want show it using loop but its fail and I can do it only manually (objects count in array is not fixet number). I am using typescript (right now self lerning this (including javascript, react-native, css, etc). My code:
const test: example[ ] = [
{ iD: '55', tP: '01', color: '80ff00'},
{ iD: '3f', tP: '00', color: 'ffffff' },
{ iD: 'fe', tP: '00', color: '2a5b3a' },
...........Other data.............
]
const showArrayOfObject=() =>{
return(
<View>
<Text style={styles.sectionDescription}>
{'nID: '+ test[0].iD + 'nType: ' + test[0].tP + 'ncolor:'+ test[0].colorB}
{'nID: '+ test[1].iD + 'nType: ' + test[1].tP + 'ncolor:'+ test[1].colorB}
{'nID: '+ test[2].iD + 'nType: ' + test[2].tP + 'ncolor:'+ test[2].colorB}
.....................................Same until end........................
</Text>
</View>
);
}
how to to this code with for, for in? Or is better way to solve this problem? P.S. My very bad english not helping at all…
I try all loops but I failed and expecting someone explain how to do that in right way.
3
Answers
You can use
Array.map
.Array.map mdn
React js docs
Since you seem to use react-native, you can render multiple components like this:
This way, you are mapping every element of your array into an HTML element that will be rendered in the DOM.
If you want to know more about this, you can check the official React documentation here: https://reactjs.org/docs/lists-and-keys.html#rendering-multiple-components
That "HTML in JS" syntax is called JSX. There you can embed JS expressions whose value will be inserted into the HTML-like syntax.
while
-loops,for
-loops and similar are statements, which are not expressions.But arrays offer methods that are functionally equivalent to
for
-loops:Array.forEach()
,Array.map()
,Since function calls are expressions, you can embed these in JSX. Usually you want to map each array value to some content. Example:
If the array entries are mapped to individual components, you should add an identifier as the component’s
key
property. Example:Why the
key
property? For performance reasons, as components may require re-rendering.For example, if a parent requires re-rendering, all its children may also. But if an identifiable child is the same as before, then it doesn’t require to be re-rendered.
Generally, you should use a unique and stable ID for each component created dynamically (e.g. iteratively).
For component-producing arrays: