[英]How to convert a forEach into a map
如何將丑陋的forEach轉換成更好的地圖?
convertedClientsToArray() {
let clientArray = [];
this.selectClients.forEach(client => {
clientArray[client.id] = client.name;
})
return clientArray
}
我已經嘗試過了,但是它沒有將ID作為鍵返回。
謝謝你的幫助
大概您想要一個包含映射到名稱的ID的對象而不是數組。
嘗試使用reduce
,傳入一個空對象作為初始化程序。
convertedClientsToArray () {
return this.selectClients.reduce((map, client) =>
((map[client.id] = client.name), map), {});
}
clientArray
必須是對象( {}
),而不是數組( []
)。 然后您可以像這樣使用reduce
:
convertedClientsToArray() {
return this.selectClients.reduce((result, client) => {
result[client.id] = client.name;
return result;
}, {}); // initial value of result is {}
}
使用數組map()方法:
var client = [ { "id": 1, "name": "alpha" }, { "id": 2, "name": "beta" }, { "id": 3, "name": "gamma" }, { "id": 4, "name": "xyz" } ]; var res = client.map(function(item) { var obj = {}; obj[item.id] = item.name; return obj; }); console.log(res);
將ES6 箭頭函數表達式與map結合使用:
var client = [ { "id": 1, "name": "alpha" }, { "id": 2, "name": "beta" }, { "id": 3, "name": "gamma" }, { "id": 4, "name": "xyz" } ]; var obj = {}; client.map(item => obj[item.id] = item.name); console.log(obj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.