Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop an object in React?

New to React and trying to loop Object attributes but React complains about Objects not being valid React children, can someone please give me some advice on how to resolve this problem? I've added createFragment but not completely sure where this needs to go or what approach I should take?

JS

var tifs = {1: 'Joe', 2: 'Jane'}; var tifOptions = Object.keys(tifs).forEach(function(key) {     return <option value={key}>{tifs[key]}</option> }); 

Render function

render() {         const model = this.props.model;          let tifOptions = {};          if(model.get('tifs')) {             tifOptions = Object.keys(this.props.model.get('tifs')).forEach(function(key) {                 return <option value={key}>{this.props.model.get('tifs')[key]}</option>             });         }          return (             <div class={cellClasses}>                      <div class="grid__col-5 text--center grid__col--bleed">                         <h5 class="flush text--uppercase">TIF</h5>                         <select id="tif" name="tif" onChange={this.handleChange}>                             {tifOptions}                         </select>                     </div>              </div>         );     } 

Error in console

If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) 
like image 543
styler Avatar asked Oct 10 '16 19:10

styler


People also ask

How do you loop an object in React JS?

Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.

Can we apply for of loop on object?

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Can we loop object in JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.


1 Answers

The problem is the way you're using forEach(), as it will always return undefined. You're probably looking for the map() method, which returns a new array:

var tifOptions = Object.keys(tifs).map(function(key) {     return <option value={key}>{tifs[key]}</option> }); 

If you still want to use forEach(), you'd have to do something like this:

var tifOptions = [];  Object.keys(tifs).forEach(function(key) {     tifOptions.push(<option value={key}>{tifs[key]}</option>); }); 

Update:

If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function:

const tifOptions = Object.keys(tifs).map(key =>      <option value={key}>{tifs[key]}</option> ) 

Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/

like image 174
tobiasandersen Avatar answered Oct 09 '22 19:10

tobiasandersen