1

I have an user object like this

user: {
name: "james",
contact: "3245234545",
email: "[email protected]"
}

and I want to display it like this

james, 3245234545, [email protected]

if it's an array I can do join(',') but it's an object unfortunately. My current approach is like this

{this.user &&
<div>
{this.user.name} ,{this.user.contact}, {this.user.email}
</div>
}

This will work but not perfect, what if user did not fill in their contact? then the extra , is still there. if the email is optional, then there will be an extra , too in the end.

1 Answer 1

2

You could use Object.keys:

{this.user &&
<div>
{Object.keys(this.user).map(key => this.user[key]).join(', ')}
</div>
}

There is also Object.entries, but it not very well supported, so you'd have to use a polyfill for that.

Also note that the order of object keys may not be the exact order you defined them in, although most browsers will preserve the order, you may want to use a Map instead.

Sign up to request clarification or add additional context in comments.

2 Comments

this won't work if the user object has other stuff like id, address, grade etc.
Well, that wasn't in the question... But you could use something like lodash _.pick(this.user, ['name', 'contact', 'email']) to pick the keys you want first.

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.