React.js right way to iterate over object instead of Object.entries
JavascriptReactjsEcmascript 6Javascript Problem Overview
I don't like using Object.entries(object).map((key, i)
because I found out that this is an experimental technology of ECMAScript 7 and I feel that something may go wrong on production. Are there any native javascript alternative?
I have no problems with values of name, price, description because I know exactly where they should be rendered and I can access them with Populate.key, but for the characteristics, I need to literate over object and render both key and value.
I tried to use Object.keys(priceChars).map(function(key, i)
but didn't understand how to separate key from value. Like, it was rendering "performance 500", but I need performance word to be in a icon class, and 500 is an actual value to be displayed.
My JSON structure
const Populate = {
'name': "Product",
'price': "1000",
'description': "Product description",
'characteristics': {
'performance': '500',
'pressure': '180',
'engine': '4',
'size': '860*730*1300',
'weight': '420'
}
}
And component
class PriceBlock extends Component {
render() {
const {priceName, priceDesc, priceVal, priceChars} = this.props;
const characteristics = Object.entries(priceChars).map((key, i) => {
return (
<div className="price__icon-row" key={i}>
<i className={'ico ico-' + key[0]}></i> <span>{key[1]}</span>
</div>
);
});
return (
<div className="col-5 price__block">
<div className="price__name">{priceName}</div>
<div className="price__description">{priceDesc}</div>
<div className="price__icons">
{characteristics}
</div>
<div className={ managePriceClass(priceVal) }>{priceVal}</div>
</div>
);
}
}
Javascript Solutions
Solution 1 - Javascript
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.
})
Solution 2 - Javascript
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>
)
})
}
}