首页 > 解决方案 > 如何将数组与对象数组连接起来?

问题描述

我有一个名为 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)
                        })
                    })

标签: javascriptarraysobject

解决方案


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);


推荐阅读