2017-10-09 115 views
0

我想返回我的箭頭函數的參數word作爲對象鍵的屬性。但返回的對象改爲包含屬性"word"作爲對象屬性的箭頭函數返回參數

lines = ["first row","second row","third row"] 
 
let newLines = lines.map((item, index)=> { 
 
        let wordsPerLines = item.split("\s"); 
 
        return wordsPerLines.map(word => ({ word : index})) 
 
      } 
 
      ); 
 
      console.log(newLines);

這是輸出:

[ 
    [ 
    { 
     "word": 0 
    }, 
    { 
     "word": 0 
    } 
    ], 
    [ 
    { 
     "word": 1 
    }, 
    { 
     "word": 1 
    } 
    ], 
    [ 
    { 
     "word": 2 
    } 
    ] 
] 

我想有這個,而不是輸出:

[ 
    [ 
    { 
     "first": 0 
    }, 
    { 
     "row": 0 
    } 
    ], 
    [ 
    { 
     "second": 1 
    }, 
    { 
     "row": 1 
    } 
    ], 
    [ 
    { 
     "third": 2 
    }, 
    { 
     "row": 2 
    } 
    ] 
] 
+0

雖然您的問題已關閉,但您在分割字符串時遇到問題。你正在把一個正則表達式作爲一個字符串。使用'.split('')'或'.split(/ \ s /)' – chazsolo

+0

@chazsolo,你是對的,謝謝! – edkeveked

回答

1

你必須把屬性名在方括號:

word => ({ [word] : index}) 

所以:

return wordsPerLines.map(word => ({ [word] : index})); 

[ ]可以包含任何表情。這是評估,並且結果的字符串值將是屬性名稱。

1

JavaScript邁出了關鍵的對象從字面上。要使用一個變量,你的返回代碼更改爲以下:

return wordsPerLines.map(word => ({ [word] : index})) 

的支架讓JS知道這是一個變量,而不是從字面上'word'