Search code examples
javascriptreactjsjsxjavascript-objects

Iterate over object properties in JSX


New to React/JSX so please bear with me. I have an API that returns an object as follows

var currObj = {
  SKU : 'Test_SKU_120934',
  category : 'Home',
  inventory_status : 1.
}

I want to iterate over this object and return a html unnumbered list as follows

<ul>
  <li> <strong>SKU</strong> : 'Test_SKU_120934'</li>
  <li> <strong>category</strong>: 'Home' </li>
  <li> <strong>inventory_status</strong> : 1 </li> 
</ul>
```
I can accomplish this in normal Javascript using 'for...in' loop. However, that loop doesn't return anything. How do I write statement below?
```
render () {
    return (

    );
}
```

Solution

  • as you got the answer in the comment you have to use the map which will return the array of children that will be rendered in the jsx.

    here is the code snippet.

    /* other react component body
    .
    .
    .
    */
    
    // targeted object
    var currObj = {
      SKU : 'Test_SKU_120934',
      category : 'Home',
      inventory_status : 1.
    }
    
    const objectList = Object.keys(currObj).map(k => (
      <li
       key={k}
      ><strong>{k}</strong>: {currObj[k]}</li>
    ));
    
    return (
    <ul>{objectList}</ul>
    );
    
    // here objectList is returned by the map function. and Object.keys function creates iterable array of keys from object.