0

What's wrong with this code? I'm trying to produce

james, 3245234545, [email protected]

class HelloWorldComponent extends React.Component {
    render() {

        const user = {
            name: "james",
            contact: "3245234545",
            email: "[email protected]",
            other: 'dsfsdfsdf'
        };

        return (      
            <div>{user &&
                <div>
                {Object.keys(user).map(key => {

                    if(key === 'name' || key==='contact' || key==='email'){
                        return user[key].join(', ')
                    }

                })}</div>
            }</div>
        )
    }
}

But I got error of

user[key].join is not a function

Here's my jsbin: http://jsbin.com/kuliwevoku/edit?js,console,output

1

1 Answer 1

3

You should join the map result:

Object.keys(user).map(key => {

                if(key === 'name' || key==='contact' || key==='email'){
                    return user[key]
                }

            }).join(', ')

You can filter the array too:

   Object.keys(user)
         .filter(key => ['name', 'contact', 'email'].includes(key))
         .map(key => user[key]).join(', ')
Sign up to request clarification or add additional context in comments.

4 Comments

Close, but this will return james, 3245234545, [email protected], . (Note the extra comma.)
True. Didn't realized that.
key !=="other" is slightly shorter... ;)
@Jonasw, that is shorter, but there may be keys besides other as well.

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.