首页 > 解决方案 > 使用 es6 向对象插入新属性

问题描述

我想在对象数组中添加新对象

const valueObj = Object.keys(values);
const filterCompetencies = competencies.filter(item =>
   item.competencies.find(i => !i.isComputational),
);

const filterComp = filterCompetencies.map(item => item.competencies);
const flatten = _.flattenDeep(filterComp);

const auditLogObj = flatten.map(item => ({
  employeeId: _.toNumber(currentUserId),
  actionName: `Updated target for ${item.name}`,
  actionDate: dateToday,
  actionBy: `${mentorSignature.firstName} ${mentorSignature.lastName}`,
}));

console.log(auditLogObj);
console.log(valueObj);

我希望我的对象插入新对象,它看起来像这样

{
  employeeId: 243,
  id: "target-3-0",
  actionBy: "Sophia Vaughn",
  actionDate: "Nov 14 2020 14:49:29 PM",
  actionName: "Updated target for Mentorship (as mentee)"
},
{
  employeeId: 243,
  id: "target-3-1",
  actionBy: "Sophia Vaughn",
  actionDate: "Nov 14 2020 14:49:29 PM",
  actionName: "Updated target for Continuous Learning"
},
{
  employeeId: 243,
  id: "target-3-2",
  actionBy: "Sophia Vaughn",
  actionDate: "Nov 14 2020 14:49:29 PM",
  actionName: "Updated target for Certifications Passed"
},
...

在此处输入图像描述

标签: javascriptecmascript-6

解决方案


最简单的方法是扩充你的映射器,以便为它创建的每个新对象,从valueObj索引中获取相应的 id:

const auditLogObj = flatten.map((item, i) => ({
  id: values[i],
  employeeId: _.toNumber(currentUserId),
  actionName: `Updated target for ${item.name}`,
  actionDate: dateToday,
  actionBy: `${mentorSignature.firstName} ${mentorSignature.lastName}`,
}));

推荐阅读