如何在 map() 中將 Id 轉換成 Value ?
栏目: JavaScript · 发布时间: 7年前
内容简介:實務上從 API 獲得的資料,可能只有 id,並沒有實際的 value,我們必須在ECMAScript 5使用 Imperative 寫法,我們會使用
實務上從 API 獲得的資料,可能只有 id,並沒有實際的 value,我們必須在 map() 內自行將 id 轉換成 value。
Version
ECMAScript 5
Imperative
const data = [
{id: 1, name: 'Sam', cityId: 1},
{id: 2, name: 'Kevin', cityId: 2},
{id: 3, name: 'Mike', cityId: 3},
];
let result = [];
for (let i = 0; i < data.length; i++) {
let city = '';
switch (data[i].cityId) {
case 1:
city = 'Taipei'
break;
case 2:
city = 'Tokyo';
break;
case 3:
city = 'Chicage';
break;
}
result.push({
id: data[i].id,
name: data[i].name,
cityId: data[i].cityId,
city: city,
});
}
console.log(result);
使用 Imperative 寫法,我們會使用 for loop 。
cityId 轉換成 city 部分,會使用 switch case ,最後在使用 Array.push() 將新的 object 塞進 result array。
Map
const data = [
{ id: 1, name: 'Sam', cityId: 1 },
{ id: 2, name: 'Kevin', cityId: 2 },
{ id: 3, name: 'Mike', cityId: 3 },
];
const cityMap = {
1: 'Taipei',
2: 'Tokyo',
3: 'Chicago',
};
const result = data.map(x => ({
...x,
city: cityMap[x.cityId],
}));
console.log(result);
Functional 寫法會透過 map() 。
cityId 轉換成 city 部分,由於 ECMAScript object 的 key / value 特性,將 switch case 改用 object 改寫。
Conclusion
Switch case
以上所述就是小编给大家介绍的《如何在 map() 中將 Id 轉換成 Value ?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Trading and Exchanges
Larry Harris / Oxford University Press, USA / 2002-10-24 / USD 95.00
This book is about trading, the people who trade securities and contracts, the marketplaces where they trade, and the rules that govern it. Readers will learn about investors, brokers, dealers, arbit......一起来看看 《Trading and Exchanges》 这本书的介绍吧!