有2个数组,分别是
countryList:[
{id:1,country:'CN',country_name:'China'},
{id:2,country:'EN',country_name:'England'},
{id:3,country:'AO',country_name:'Angola'},
{id:4,country:'AR',country_name:'Argentina'},
];
worldMapList[
{id:1,name:'CN'},
{id:2,name:'AR'}
];
需求: 给worldMapList 新增 countryName 属性
目标数组如下:
worldMapList[
{id:1,name:'CN',countryName:'China'},
{id:2,name:'AR',countryName:'Argentina'}
];
方法1: 双循环 赋属性; 时间复杂度为 n2.
方法2: 将countryList 哈希成 对象,然后 只遍历 countryList即可, 时间复杂度为n.
const obj = {};
this.countryList.forEach(item => {
obj[item.country] = item.country_name;
});
this.worldMapList.forEach(item => {
item.countryName = obj[item.name];
});