javascript - 如何将数组与对象数组连接起来?
问题描述
我有一个名为 Indicators 的对象数组和一个名为 Departments 的数组
对于每个指标,我应该添加每个部门。所以如果有4个部门,应该有4个指标相同,但部门不同。我怎样才能做到这一点?
编辑:这是我的代码
let arrDepartment = []
this.DepartmentIR.forEach(e=>{
arrDepartment.push(e.Department)
})
this.RisksIndicatorsIR.forEach(e=>{
let x = {...e}
x.Departments = arrDepartment
console.log(x)
})
})
解决方案
const departments = [
"department1",
"department2",
"department3",
"department4"
];
const indicators = [
{ name: "indicators1", id: 95 },
{ name: "indicators2", id: 92 },
{ name: "indicators3", id: 93 },
{ name: "indicators4", id: 94 }
];
// Solution with forEach - all departments as key on each indicator
const newIndicators = [];
indicators.forEach((x) =>
newIndicators.push({ ...x, departments: departments })
);
console.log("Solution with forEach", newIndicators);
// Solution with Reduce - all departments as key on each indicator
const newIndicatorsArr = indicators.reduce((acc, x) => {
acc.push({ ...x, departments: departments });
return acc;
}, []);
console.log("Solution with Reduce", newIndicatorsArr);
// Solution if you want 1 department per indicator
const oneDepartmentPerIndicator = indicators.reduce((acc, x, i) => {
acc.push({ ...x, departments: departments[i] });
return acc;
}, []);
console.log("Solution with 1 department per indicator", newIndicatorsArr);
推荐阅读
- ios - [Swift]我无法从特定 URL 获取任何 JSON 数据
- python - 返回一个数字是否为素数作为 Python 中的布尔值
- javascript - 由于滥用状态,数组未动态更新
- ffmpeg - 从实时 youtube 流中提取帧
- javascript - 为什么此代码在松散相等而不是严格相等时正确运行?
- reactjs - 无法在 HOC 中将钩子用于功能组件
- ios - iOS提交:无效二进制:禁止指令
- google-bigquery - Bigquery中的openstreet地图数据集中缺少美国几何
- javascript - ReferenceError:logInModule 未在 HTMLElement.onclick 中定义
- mysql - 在最后一步安装 Mysql 时出现问题,需要很长时间