javascript - JS(ES6): Merge arrays based on id and concatenating sub arrays

标签 javascript arrays merge ecmascript-6 array-merge

我有两个数组,如下所示:

const persons = [
  {
    id: 1,
    name: 'Peter',
    job: 'Programmer'
  },
  {
    id: 2,
    name: 'Jeff',
    job: 'Architect'
  },
];

const salaries = [
  {
    id: 1,
    salary: 3000,
    departments: ['A', 'B'] 
  },
  {
    id: 1,
    salary: 4000,
    departments: ['A', 'C']
  },
  {
    id: 2,
    salary: 4000,
    departments: ['C', 'D']
  }
];

现在我需要以某种方式将这些数组合并为一个,以便每个 id 只存在一次。应该替换相同的键,除非它是一个数组,然后我希望它们添加/连接。所以想要的结果应该是这样的:

const result = [
  {
    id: 1,
    name: 'Peter',
    job: 'Programmer',
    salary: 4000,
    departments: ['A', 'B', 'C'] 
  },
  {
    id: 2,
    name: 'Jeff',
    job: 'Architect',
    salary: 4000,
    departments: ['C', 'D']
  }
];

我已经尝试过:

// double id's, arrays get replaced
Object.assign({}, persons, salaries)

// loadsh: double id's, arrays get concatenated
_.mergeWith(persons, salaries, (objValue, srcValue) => {
    if (_.isArray(objValue)) {
        return objValue.concat(srcValue);
    }
});

// gives me a map but replaces arrays
new Map(salaries.map(x => [x.id, x])

有人知道如何实现这一目标吗?

最佳答案

您可以使用map() , filter() , reduce() , Object.assign()Spread syntax达到所需的结果。

演示

const persons = [{
    id: 1,
    name: 'Peter',
    job: 'Programmer'
  }, {
    id: 2,
    name: 'Jeff',
    job: 'Architect'
  }],
  salaries = [{
    id: 1,
    salary: 3000,
    departments: ['A', 'B']
  }, {
    id: 1,
    salary: 4000,
    departments: ['A', 'C']
  }, {
    id: 2,
    salary: 4000,
    departments: ['C', 'D']
  }];


let output = persons.map(obj => {
  let filter = salaries.filter(v => v.id == obj.id);
  if (filter) {
    let departments = filter.reduce((r, v) => [...v.departments, ...r], []);
    Object.assign(obj, {
      salary: filter[filter.length - 1].salary,
      departments: departments.filter((item, pos) => departments.indexOf(item) == pos).sort()
    });
  }
  return obj;
});

console.log(output)

关于javascript - JS(ES6): Merge arrays based on id and concatenating sub arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49649360/

相关文章:

java - 如何检查数组与参数的值是否相同?

javascript - 按钮显示进度

javascript - 使用js更新表单字段但未在提交的数据中显示

php - 在 PHP 中将数组转换为字符串

sql - 合并到 sqlserver - 语法不正确

r - data.table 按多列合并

version-control - TFS:跨团队项目共享脚本的分支注意事项

javascript - 未捕获的 ReferenceError 函数未定义

javascript - Chrome 标签焦点索引 API

python - 通过python以特定方式计算嵌套数组的平均值?