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

tej*_*t19 2 javascript arrays

我试图将包含字符串值的对象数组转换为基于其他对象数组的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
  }
];
Run Code Online (Sandbox Code Playgroud)

我希望转换后的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}
]
Run Code Online (Sandbox Code Playgroud)

我试过了:

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.
});
Run Code Online (Sandbox Code Playgroud)

我从使用所期望的结果forEach我有,但我认为是用一个更好的方式.filter().reduce().我想帮助消除两者的最后一行forEach语句,我必须设置row.department = row.department.idrow.location = row.location.id

rai*_*7ow 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 };
});
Run Code Online (Sandbox Code Playgroud)

换句话说,您可以使用Array.prototype.find()而不是filter-reducecombo.由于.reduce()不会在第一次成功搜索时停止,因此.find()更加高效和简洁.只是不要忘记为IE和其他非支持性浏览器应用polyfill.