我正在尝试将包含字符串值的对象数组转换为基于其他对象数组的id值。这是阵列。
const employees = [
{
name: 'bob',
department: 'sales',
location: 'west'
},
{
name:'fred',
department: 'sales',
location: 'west'
},
{
name:'josh',
department: 'inventory',
location: 'east'
},
{
name: 'mike',
department: 'quality assurance',
location: 'north'
}
];
const departments = [
{
dep: 'sales',
id: 12
},
{
dep:'quality assurance',
id: 11
},
{
dep:'inventory',
id: 13
}
];
const locations = [
{
region: 'west',
id: 3
},
{
region:'north',
id: 1
},
{
region:'east',
id: 2
},
{
region:'south',
id: 4
}
];
我希望转换后的employees数组看起来像这样:
[
{name:"bob", department: 12, location: 3},
{name:"fred", department: 12, location: 3},
{name:"josh", department: 13, location: 2},
{name:"mike", department: 11, location: 1}
]
我试过了:
employees.forEach((row) => {
row.department = departments.filter(depart => row.department === depart.dep)
.reduce((accumulator, id) => id)
row.department = row.department.id; // would like to remove this.
});
employees.forEach((row) => {
row.location = locations.filter(loc => row.location === loc.region)
.reduce((accumulator, id) => id);
row.location = row.location.id; // would like to remove this part.
});
我使用forEach
获得了所需的结果,但我认为有更好的方法可以使用.filter()
和.reduce()
。我想帮助删除我必须设置forEach
和row.department = row.department.id
row.location = row.location.id
语句的最后一行
答案 0 :(得分:5)
一种可能的方法:
const dehydratedEmployees = employees.map(emp => {
const depId = departments.find(dep => dep.dep === emp.department).id;
const locId = locations.find(loc => loc.location === loc.region).id;
return { name: emp.name, department: depId, location: locId };
});
换句话说,您可以使用Array.prototype.find()代替filter-reduce
组合。由于.reduce()
在第一次成功搜索时不会停止,.find()
更加高效和简洁。只是不要忘记为IE和其他不支持的浏览器应用polyfill。
答案 1 :(得分:2)
一种解决方案是为部门和地点创建Map
,以便在映射employees
时消除嵌套循环。
可以从嵌套数组创建Map
:new Map([[key, value], [key, value]])
:
const employees = [
{ name: 'bob', department: 'sales', location: 'west' },
{ name:'fred', department: 'sales', location: 'west' },
{ name:'josh', department: 'inventory', location: 'east' },
{ name: 'mike', department: 'quality assurance', location: 'north'}
];
const departments = [
{ dep: 'sales', id: 12 },
{ dep:'quality assurance', id: 11 },
{ dep:'inventory', id: 13}
];
const locations = [
{ region: 'west', id: 3 },
{ region:'north', id: 1},
{ region:'east', id: 2 },
{ region:'south', id: 4}
];
const departmentMap = new Map(departments.map(i => [i.dep, i.id]));
const locationMap = new Map(locations.map(i => [i.region, i.id]));
const result = employees.map(e => ({
name: e.name,
department: departmentMap.get(e.department),
location: locationMap.get(e.location)
}))
console.log(result);
答案 2 :(得分:1)