1

Please let me know how I can optimize more below code in one line:

 {addressToDisplay?.addressLineOne}
      {addressToDisplay?.addressLineTwo}
      {addressToDisplay?.city}
      {addressToDisplay?.state}
      {addressToDisplay?.zip}
1
  • only for those attributes? or all of values in addressToDisplay? let me know what addressToDisplay has and how it looks like Commented Apr 21, 2022 at 5:47

3 Answers 3

1

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` `}</>
Sign up to request clarification or add additional context in comments.

Comments

0

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]}</>)}

4 Comments

I need to display four value like city,state,lineone and line two.How i can show here.If we use key and value it will display all the values in addressTodisplay
@user2110253 updated answer according to the above comment.
giving error TypeError: Cannot read properties of undefined (reading 'addressLineOne')
You can change last line to {addressToDisplay && addressField.map(key => <>{addressToDisplay[key]}</>)}
0

{addressToDisplay && addressField.map((key) => <>{addressToDisplay[key]}</>)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.