gpt4 book ai didi

javascript - 从字符串名称到 id 的过滤对象数组

转载 作者:行者123 更新时间:2023-12-04 01:54:38 24 4
gpt4 key购买 nike

我正在尝试将包含字符串值的对象数组转换为其基于其他对象数组的 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
}
];

我希望转换后的员工数组看起来像这样:

[
{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( )。我想帮助删除我必须设置 row.department = row.department.idrow.location = row 的两个 forEach 语句的最后一行.location.id

最佳答案

一种可能的方法:

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。

关于javascript - 从字符串名称到 id 的过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49415766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com