0

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

james, 3245234545, james@gmail.com

class HelloWorldComponent extends React.Component {
    render() {

        const user = {
            name: "james",
            contact: "3245234545",
            email: "james@gmail.com",
            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

Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35
  • Possible duplicate of [Why is my join on a JavaScript array failing?](http://stackoverflow.com/questions/1424710/why-is-my-join-on-a-javascript-array-failing) – Shridhar R Kulkarni May 07 '17 at 17:01

1 Answers1

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(', ')
CD..
  • 72,281
  • 25
  • 154
  • 163