2017-05-07 106 views
0

這段代碼有什麼問題?我試圖產生對象鍵錯誤key.join不是函數

詹姆斯,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> 
     ) 
    } 
} 

但我得到

用戶的錯誤[關鍵]。加入不是功能

這是我的jsbin:http://jsbin.com/kuliwevoku/edit?js,console,output

+0

的可能的複製[爲什麼我加入一個JavaScript陣列失敗了?](HTTP ://stackoverflow.com/questions/1424710/why-is-my-join-on-a-javascript-array-failing) –

回答

3

你應該joinmap結果:

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

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

      }).join(', ') 

可以過濾陣列太:

Object.keys(user) 
     .filter(key => ['name', 'contact', 'email'].includes(key)) 
     .map(key => user[key]).join(', ') 
+0

關閉,但是這會返回'james,3245234545,[email protected],'。 (請注意額外的逗號。) –

+0

正確。沒有意識到這一點。 –

+0

key!==「other」稍微短一些......;) –

相關問題