Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js right way to iterate over object instead of Object.entries

People also ask

How do you iterate over an object in Reactjs?

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 you iterate over an object?

Object. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.

Can you pass objects as props in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.


a = { 
  a: 1,
  b: 2,
  c: 3
}

Object.keys(a).map(function(keyName, keyIndex) {
  // use keyName to get current key's name
  // and a[keyName] to get its value
})

A newer version, using destructuring and arrow functions. I'd use this one for new code:

a = { 
  a: 1,
  b: 2,
  c: 3
}

Object.entries(a).map(([key, value]) => {
    // Pretty straightforward - use key for the key and value for the value.
    // Just to clarify: unlike object destructuring, the parameter names don't matter here.
})

Complete function render in react

const renderbase = ({datalist}) => {
        if(datalist){
            return  Object.keys(datalist).map((item,index) => {
                return(
                  <option value={datalist[item].code} key={index}>
                      {datalist[item].symbol}
                  </option>
                )
            })
        }  
    }