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

时间:2018-03-21 20:17:03

标签: 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
  }
];

我希望转换后的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()。我想帮助删除我必须设置forEachrow.department = row.department.id

的两个row.location = row.location.id语句的最后一行

3 个答案:

答案 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时消除嵌套循环。
可以从嵌套数组创建Mapnew 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)

另一种可能的方法。您可以使用 Array.prototype.filter() (如下所示)

api/ger/getDetail