Home > Mobile >  Is possible to access variables in array of oject like that (TypeScript)?
Is possible to access variables in array of oject like that (TypeScript)?

Time:01-22

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.

CodePudding user response:

You can use Array.map.

Array.map mdn React js docs

const showArrayOfObject=({ someArray }) =>{

 return(
  <View>
  <Text style={styles.sectionDescription}>
    {someArray.map((arrayItem)=> <div key={arrayItem.id}>{arrayItem.id}</div>)}
  </Text>
</View>
 ); 
}

CodePudding user response:

Since you seem to use react-native, you can render multiple components like this:

const showArrayOfObject=() =>{

  return(
    <View>
      <Text style={styles.sectionDescription}>
        {example.map((element) =>
          <div key={element.toString()}>{'\nID: '  element.iD   '\nType: '   element.tP   '\ncolor:'  element.color}</div>
        )}
      </Text>
    </View>
  ); 

}

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

CodePudding user response:

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:

Since function calls are expressions, you can embed these in JSX. Usually you want to map each array value to some content. Example:

const data = ["First sentence.", "Second sentence."];

function MyElement() {
  return (<p>{data.join(" ")}</p>);
}

const app = document.getElementById("app");
ReactDOM.render(<MyElement></MyElement>, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

If the array entries are mapped to individual components, you should add an identifier as the component's key property. Example:

const data = ["First paragraph.", "Second paragraph."];

function MyElement() {
  return (<p>
    {data.map((text, i) => (
      // Prefer unique stable IDs over indices; read along for an explanation.
      <p key={i}>{text}</p>
    ))}
  </p>);
}

const app = document.getElementById("app");
ReactDOM.render(<MyElement></MyElement>, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>


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:

  • If its order is stable, then so will be its indices. These indices can be used as IDs.
  • If its items are swapped or shifted, then their corresponding indices change too. These indices should not be used as IDs.
  • Related