'Optimize the display value in React Js
Please let me know how I can optimize more below code in one line:
{addressToDisplay?.addressLineOne}
{addressToDisplay?.addressLineTwo}
{addressToDisplay?.city}
{addressToDisplay?.state}
{addressToDisplay?.zip}
Solution 1:[1]
You can try this out:
Object.keys(addressToDisplay).map(function(key) {
return <>{ addressToDisplay[key] }</>
})
And to display both key, value you can add:
Object.entries(addressToDisplay).map(([key, val]) =>
<h2 key={key}>{key}: {val}</h2>
)
If you need specific values then you can store the keys which you need in one array
addressField = ['city', 'state', 'lineone', 'linetwo']
and then get them by
{addressToDisplay && addressField.map(key => <>{addressToDisplay[key]}</>)}
Solution 2:[2]
if your object is already well organized you can do this
return <>{[...Object.values(addressToDisplay || {})].join` `}</>;
Or else you have this kind of solution
const {addressLineOne, addressLineTwo, city, state, zip} = addressToDisplay || {};
return <>{[addressLineOne, addressLineTwo, city, state, zip].join` `}</>
Solution 3:[3]
{addressToDisplay && addressField.map((key) => <>{addressToDisplay[key]}</>)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | vsync |
Solution 3 | user2110253 |